xml建模+自定义mvc(增加,删除,修改)

这里写目录标题

    • 前言
    • 1、什么是xml建模?
    • 2、建模是否更快捷更高效率呢?
    • 案例详解
    • 自定义mvc
    • 增加
    • 删除
    • 修改
    • 总结

前言

1、什么是xml建模?

我们都知道.xml文件有两个作用,一是传输,二是存储数据。xml建模主要针对它的第二的功能开发的,在我们解析.xml文件我们可以发现,要写大量的代码最后得到一个数据。

2、建模是否更快捷更高效率呢?

简单的来说,就是写一些方法将xml解析变得高效,和简单,这就是xml建模。也是我们为什么要xml建模的原因(减少代码量,并且可以针对不同的需求)。

案例详解

1、分析需要被建模的文件中有那几个对象

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
  	<servlet-name>jrebelServlet</servlet-name>
  	<servlet-class>com.zking.xml.JrebelServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>jrebelServlet</servlet-name>
  	<url-pattern>/jrebelServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
  	<servlet-name>jrebelServlet2</servlet-name>
  	<servlet-class>com.zking.xml.JrebelServlet2</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>jrebelServlet</servlet-name>
  	<url-pattern>/jrebelServlet2</url-pattern>
  	<url-pattern>/jrebelServlet3</url-pattern>
  </servlet-mapping>
</web-app>

建模步骤:

  • 根据以上代码,把元素看做是对象建(从里到外开始建)
  • xml建模+自定义mvc(增加,删除,修改)_第1张图片
    NameModel(Servlet-name)
  package com.liuchunming.model;

public class NameModel {
	public String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "NameModel [name=" + name + "]";
	}
}

UrlModel(url-pattern)

package com.liuchunming.model;

public class UrlModel {
	
	public String pattern;//url-pattern内容

	public String getPattern() {
		return pattern;
	}

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}
	
	@Override
	public String toString() {
		return "UrlModel [pattern=" + pattern + "]";
	}
	
}

ClassModel (Servlet-class)

package com.liuchunming.model;

public class ClassModel {
	public String clas;

	public String getClas() {
		return clas;
	}

	public void setClas(String clas) {
		this.clas = clas;
	}
	@Override
	public String toString() {
		return "ClassModel [clas=" + clas + "]";
	}
}

MappingModel(Servlet-mappinf)

package com.liuchunming.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MappingModel {
	private NameModel urlName; 
	private List<UrlModel> UrlModels =new ArrayList<UrlModel>();
	public NameModel getUrlName() {
		return urlName;
	}
	public void setUrlName(NameModel urlName) {
		this.urlName = urlName;
	}
	public List<UrlModel> getUrlModels() {
		return UrlModels;
	}
	public void setUrlModels(List<UrlModel> urlModels) {
		UrlModels = urlModels;
	}
	//存
	public void push(UrlModel url) {
		UrlModels.add(url);
	}
	//取
	public List<UrlModel> popp() {
		return UrlModels;
	}
	@Override
	public String toString() {
		return "MappingModel urlName=" + urlName + ", UrlModels=" + UrlModels;
	}
}

ServletModel(Servlet)

package com.liuchunming.model;

public class ServletModel {
	private NameModel NameModel;//servlet-name
	private ClassModel ClassModel;//servlet-class
	
	public NameModel getNameModel() {
		return NameModel;
	}
	public void setNameModel(NameModel nameModel) {
		NameModel = nameModel;
	}
	public ClassModel getClassModel() {
		return ClassModel;
	}
	public void setClassModel(ClassModel classModel) {
		ClassModel = classModel;
	}
	@Override
	public String toString() {
		return "ServletModel [NameModel=" + NameModel + ", ClassModel=" + ClassModel + "]";
	}
}

WebModel(web-app)

package com.liuchunming.model;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class WebModel {
	private Map<String, ServletModel> serModel=new HashMap<String, ServletModel>();
	private Map<String, MappingModel> ingModel=new HashMap<String, MappingModel>();
	private NameModel key;
	
	public NameModel getKey() {
		return key;
	}
	public void setKey(NameModel key) {
		this.key = key;
	}
	//取
	public ServletModel pop(String name) {
		return serModel.get(name);
	}
	//取
	public MappingModel popp(String mpp) {
		return ingModel.get(mpp);
	}
	//存
	public void push(ServletModel ser) {
		serModel.put(key.getName(), ser);
	}
	//存
	public void push(MappingModel mppmodel) {
		ingModel.put(key.getName(), mppmodel);
	}
	
	
	@Override
	public String toString() {
		return "WebModel [serModel=" + serModel + ", ingModel=" + ingModel + ", key=" + key + "]";
	}
	public String get(String url) {
		String name=null;
		Set<Entry<String, MappingModel>> entrySet = ingModel.entrySet();
		for (Entry<String, MappingModel> entry : entrySet) {
			//获取到值
			MappingModel mml = entry.getValue();
			//如果内容中含有url值那么则获取到servletModel对象
			if(mml.toString().contains(url)) {
				NameModel nml =mml.getUrlName();
				//将值返回出去
				name=nml.getName();
			}
		}
		return name;
	}
	
}

到这一步已经差不多建模完成了,还差最后一步工厂类
WebModelFactory

package com.liuchunming.model;

import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class WebModelFactory {
	public static WebModel build(String path) throws Exception {
		//获取需要读取的文件
		InputStream in = WebModelFactory.class.getResourceAsStream(path);
		//demoj4里的一个工具类
		SAXReader reader=new SAXReader();
		//读取
		Document document = reader.read(in);
		
		WebModel webmodel=new WebModel();
		ServletModel servletmodel=null;
		MappingModel mappmodel=null;
		NameModel nameModel=null;
		ClassModel classModel=null;
		UrlModel urlModel=null;
		//查到web-app里的全部servlet一组
		List<Element> servletModels = document.selectNodes("/web-app/servlet");
		//遍历
		for (Element EeleModel : servletModels) {
			servletmodel =new ServletModel();
			nameModel=new NameModel();
			classModel =new ClassModel();
			mappmodel =new MappingModel();
			urlModel =new UrlModel();
			//查当个
			Element Servletname = (Element) EeleModel.selectSingleNode("servlet-name");
			Element ServletClass = (Element) EeleModel.selectSingleNode("servlet-class");
			nameModel.setName(Servletname.getText());
			classModel.setClas(ServletClass.getText());
			servletmodel.setNameModel(nameModel);
			servletmodel.setClassModel(classModel);
			webmodel.setKey(nameModel);
			webmodel.push(servletmodel);
			
		}
		List<Element> mappingModels = document.selectNodes("/web-app/servlet-mapping");
		for (Element mappingModel : mappingModels) {
			mappmodel =new MappingModel();
			nameModel=new NameModel();
			
			Element Name = (Element) mappingModel.selectSingleNode("servlet-name");

			nameModel.setName(Name.getText());
			mappmodel.setUrlName(nameModel);
			
			List<Element> urlPatterns = mappingModel.selectNodes("url-pattern");
			for (Element urlPattern : urlPatterns) {
				urlModel =new UrlModel();
				urlModel.setPattern(urlPattern.getText());
				mappmodel.push(urlModel);
				webmodel.setKey(nameModel);
			}
			webmodel.push(mappmodel);
		}
		return webmodel;
	}
	
	public static WebModel build() throws Exception {
		return build("/web.xml");
	}
	public static void main(String[] args) throws Exception {
		String name = build().get("/jrebelServlet");
		System.out.println(name);
		ServletModel servletModel = build().pop(name);
		ClassModel cml = servletModel.getClassModel();
		String clas = cml.getClas();
		System.out.println(clas);
		/*servlet*/
	 	/*ServletModel pop = wm.pop("jrebelServlet");
		System.out.println(pop.getClassModel().getClas());
		System.out.println(pop.getNameModel().getName());*/
	}
}

运行结果:
xml建模+自定义mvc(增加,删除,修改)_第2张图片

自定义mvc

增加

效果图:
xml建模+自定义mvc(增加,删除,修改)_第3张图片
xml建模+自定义mvc(增加,删除,修改)_第4张图片

删除

xml建模+自定义mvc(增加,删除,修改)_第5张图片

修改

xml建模+自定义mvc(增加,删除,修改)_第6张图片
实现代码:
Dao方法

package com.liuchunming.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.liuchunming.dao.BaseDao.Callback;
import com.liuchunming.entity.Solr;
import com.liuchunming.util.DBAccess;
import com.liuchunming.util.PageBean;

public class SolrDao extends BaseDao<Solr>{
	
	/**
	 * 查询所有 模糊查询
	 * @param stu
	 * @return
	 */
	public List<Solr> find(Solr s){
		List<Solr> stulist = new ArrayList<Solr>();
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select *from t_solr_job where 1=1";
		/*//如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
		if(StringUtils.isNotBlank(s.getSname())) {
			sql+=" and (sname like '%"+s.getSname()+"%')";
		}*/
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			Solr sa =null;
			while(rs.next()) {
				sa =new Solr();
				sa.setId(rs.getString("id"));
				sa.setJob(rs.getString("job"));
				sa.setCompany(rs.getString("company"));
				sa.setAddress(rs.getString("address"));
				sa.setSalary(rs.getString("salary"));
				sa.setUrl(rs.getString("url"));
				sa.setLimit(rs.getString("limito"));
				sa.setTime(rs.getString("time"));
				stulist.add(sa);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			DBAccess.close(con,ps,rs);
		}
		return stulist;
	}
	
	
	public List<Solr> find(Solr stu,PageBean pageBean){
		List<Solr> stulist = new ArrayList<Solr>();
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select *from t_solr_job where 1=1";
		/*//如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
		if(StringUtils.isNotBlank(stu.getSname())) {
			sql+=" and (sname like '%"+stu.getSname()+"%')";
		}*/
		return this.executeQuery(sql, pageBean, new Callback<Solr>() {

			@Override
			public List<Solr> foreach(ResultSet rs) throws SQLException {
				// 不同的内容
				Solr sa =null;
				while(rs.next()) {
					sa =new Solr();
					sa.setId(rs.getString("id"));
					sa.setJob(rs.getString("job"));
					sa.setCompany(rs.getString("company"));
					sa.setAddress(rs.getString("address"));
					sa.setSalary(rs.getString("salary"));
					sa.setUrl(rs.getString("url"));
					sa.setLimit(rs.getString("limito"));
					sa.setTime(rs.getString("time"));
					stulist.add(sa);
				}
				return stulist;
			}
		});
	}
	
	public int add(Solr s) {
		int n=0;
		Connection con=null;
		PreparedStatement ps=null;
		String sql="insert into t_solr_job(id,job,company,address,salary,url,limito,time,descc)values(?,?,?,?,?,?,?,?,'暂无')";
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			ps.setString(1, s.getId());
			ps.setString(2, s.getJob());
			ps.setString(3, s.getCompany());
			ps.setString(4, s.getAddress());
			ps.setString(5, s.getSalary());
			ps.setString(6, s.getUrl());
			ps.setString(7, s.getLimit());
			ps.setString(8, s.getTime());
			n=ps.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}finally {
			DBAccess.close(con, ps, null);
		}
		return n;
	}
	
	public int del(Solr s) {
		int n=0;
		Connection con=null;
		PreparedStatement ps=null;
		String sql="delete from t_solr_job where id="+s.getId();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			n=ps.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
		return n;
	}
	public Solr byid(Solr s) {
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select *from t_solr_job where id="+s.getId();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			if(rs.next()) {
				s.setId(rs.getString("id"));
				s.setJob(rs.getString("job"));
				s.setCompany(rs.getString("company"));
				s.setAddress(rs.getString("address"));
				s.setSalary(rs.getString("salary"));
				s.setUrl(rs.getString("url"));
				s.setLimit(rs.getString("limito"));
				s.setTime(rs.getString("time"));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return s;
	}
	
	public int eidt(Solr s) {
		int n=0;
		Connection con=null;
		PreparedStatement ps=null;
		System.out.println(s.getId());
		String sql="update  t_solr_job set id=?,job=?,company=?,address=?,salary=?,url=?,limito=?,time=? where id="+s.getId();
		try {
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			ps.setString(1, s.getId());
			ps.setString(2, s.getJob());
			ps.setString(3, s.getCompany());
			ps.setString(4, s.getAddress());
			ps.setString(5, s.getSalary());
			ps.setString(6, s.getUrl());
			ps.setString(7, s.getLimit());
			ps.setString(8, s.getTime());
			n=ps.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}finally {
			DBAccess.close(con, ps, null);
		}
		return n;
	}
	
	/**
	 * 专门写一个方法用来拼接查询语句的统计满足条件的总行数
	 * @param sql 满足条件的sql
	 * @return
	 */
	public String getCountSql(String sql) {
		return "select count(*) from ("+sql+") t1";
	}
	/**
	 * 专门写一个方法用来存储分页的sql
	 * @param sql 	查询指定页码并满足条件的sql
	 * @param pageBean
	 * @return
	 */
	public String getPageSql(String sql,PageBean pageBean) {
		
		return sql+" limit "+pageBean.getStartsIndex()+","+pageBean.getRows()+"";
	}
}

jsp界面:增加

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>




Insert title here


增加

编       号:
职       位:
公       司:
工作地址:
薪       资:
链       接:
学       历:
时       间:

Servlet:增加

package com.liuchunming.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuchunming.dao.SolrDao;
import com.liuchunming.entity.Solr;

public class SolrServlet extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		String job = req.getParameter("job");
		String company = req.getParameter("company");
		String address = req.getParameter("address");
		String salary = req.getParameter("salary");
		String url = req.getParameter("url");
		String limit = req.getParameter("limit");
		String time = req.getParameter("time");
		Solr s=new Solr();
		s.setId(id);
		s.setJob(job);
		s.setCompany(company);
		s.setAddress(address);
		s.setSalary(salary);
		s.setUrl(url);
		s.setLimit(limit);
		s.setTime(time);
		SolrDao sd=new SolrDao();
		int n = sd.add(s);
		if(n>0) {
			req.getRequestDispatcher("studentAction.action").forward(req, resp);
		}else {
			resp.getWriter().println("");
		}
	}
}

servlet删除

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = req.getParameter("id");
		Solr s=new Solr();
		s.setId(id);
		SolrDao sd=new SolrDao();
		int n = sd.del(s);
		if(n>0) {
			req.getRequestDispatcher("studentAction.action").forward(req, resp);
		}else {
			resp.getWriter().println("");
		}
	}

servlet:修改

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String sid = req.getParameter("sid");
		String id = req.getParameter("id");
		String job = req.getParameter("job");
		String company = req.getParameter("company");
		String address = req.getParameter("address");
		String salary = req.getParameter("salary");
		String url = req.getParameter("url");
		String limit = req.getParameter("limit");
		String time = req.getParameter("time");
		System.out.println("servlet"+sid);
		System.out.println("servlet"+id);
		Solr s=new Solr();
		/*if(id!=null) {
			s.setId(id);
		}*/
		s.setId(id);
		s.setJob(job);
		s.setCompany(company);
		s.setAddress(address);
		s.setSalary(salary);
		s.setUrl(url);
		s.setLimit(limit);
		s.setTime(time);
		SolrDao sd=new SolrDao();
		int n = sd.eidt(s);
		if(n>0) {
			req.getRequestDispatcher("studentAction.action").forward(req, resp);
		}else {
			resp.getWriter().println("");
		}
	}

总结

MVC的优点在于关注点分享,够灵活,可扩展,可测试性。可在action级别上进行单元测试,webform恐怕不容易测试吧?生成客户端更标准,利于搜索引擎友好
今天分享到这里,有写的不好的地方欢迎大家提出来改进
查询及分页建模详细链接:
https://blog.csdn.net/licmi/article/details/106225291.

你可能感兴趣的:(xml建模+自定义mvc(增加,删除,修改))