自定义MV3

自定义MVC(三)-优化

我们 完成上篇博客的最后一步,进行优化,我们已经把工具类都写好了,接下来我们可以把自己写好的工具类打成一个jar包,来测试调用可不可行
点击Export -> 点击 JAR File ->

自定义MV3_第1张图片
勾选你要打成jar包的工具类,我在这里全部勾选了
自定义MV3_第2张图片

保存到你要保存的位置

接下来我们重新创建一个项目,把我们的jar包导进来进行测试
自定义MV3_第3张图片
写了一个book实体类

    private int bid;
	private String bname;
	private float price;

创建通用dao方法

BaseDao

package util;

import java.lang.reflect.Field;
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 entity.Book;

public class BaseDao {
	private static final String T = null;
	
	Connection con=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	public List executeQuery(String sql,Class clz,PageBean pagebean) throws InstantiationException, IllegalAccessException, SQLException{
			List list;
			try {
				list = new ArrayList<>();
				con = DBAccess.getConnection();
				if (pagebean != null && pagebean.isPagination()) {
					//该分页了
					String countSql=getCountSql(sql);
					ps=con.prepareStatement(countSql);
					rs=ps.executeQuery();
					if(rs.next()) {
						pagebean.setTotal(rs.getLong(1)+"");
					}
					
					String pageSql=getPageSql(sql,pagebean);
					ps=con.prepareStatement(pageSql);
					rs=ps.executeQuery();
					
				} else {
					ps = con.prepareStatement(sql);
					rs = ps.executeQuery();

				}
				while (rs.next()) {
					
					T t = (T) clz.newInstance();
					Field[] fields = clz.getDeclaredFields();
					for (Field field : fields) {
						field.setAccessible(true);
						field.set(t, rs.getObject(field.getName()));
					}
					list.add(t);
				} 
			} finally {
				// 
				DBAccess.close(con);
			}
				return list;
	}
	
	
	private String getPageSql(String sql, PageBean pagebean) {
		return sql + " limit "+pagebean.getStartIndex() +","+pagebean.getRows();
	}
	private String getCountSql(String sql) {
		// TODO Auto-generated method stub
		return "select count(1) from ("+sql+") t";
	}
	
	/**
	 * 通用的增删改方法
	 * @param sql  增删改sql语句
	 * @param attrs    ?所代表的数据库的实体类的属性
	 * @param t       实体类的实例
	 * @return
	 * @throws SQLException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public int executeUpdate(String sql,String[] attrs,T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		Connection con = DBAccess.getConnection();
		PreparedStatement ps = con.prepareStatement(sql);
		for (int i = 0; i < attrs.length; i++) {
			Field field = t.getClass().getDeclaredField(attrs[i]);
			field.setAccessible(true);
			ps.setObject(i+1, field.get(t));
			
		}
		return ps.executeUpdate();
	}

}

继承通用BaseDao方法

** BookDao **

package dao;

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

import com.mysql.jdbc.StringUtils;

import entity.Book;
import util.BaseDao;
import util.DBAccess;
import util.PageBean;

public class BookDao extends BaseDao{
	
	public List list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql="select * from t_mvc_book where 1=1";
		if(util.StringUtils.isNotBlank(book.getBname())) {
			sql+=" and bname like '%"+book.getBname()+"%'";
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}

	//增加
	public int add(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		String sql="insert into t_mvc_book values(?,?,?)";
		return super.executeUpdate(sql, new String[] {"bid","bname","price"}, book);
	}
	//删除
	public int delete(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		String sql="delete from t_mvc_book where bid=?";
		return super.executeUpdate(sql, new String[] {"bid"}, book);
	}
	//修改
	
	public int update(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		String sql="update t_mvc_book set bname=?,price=? where bid=?";
		return super.executeUpdate(sql, new String[] {"bname","price","bid"}, book);
	}
	
}

通用分页

Page Bean

package util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * 分页工具类
 *
 */
public class PageBean{

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页

	private String url;
	private Map paramMap = new HashMap<>();

	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		// getRequestURL获取到浏览器请求的全路径
		this.setUrl(req.getRequestURL().toString());
		// getParameterMap可以获取到一次url请求所携带的所有参数
		this.setParamMap(req.getParameterMap());

	}

	public void setPagination(String pagination) {
		if (StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	}

	public void setRows(String rows) {
		if (StringUtils.isNotBlank(rows))
			this.setRows(Integer.valueOf(rows));

	}

	public void setPage(String page) {
		if (StringUtils.isNotBlank(page)) {
			this.setPage(Integer.valueOf(page));
		}
	}

	public PageBean() {
		super();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map paramMap) {
		this.paramMap = paramMap;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

	/**
	 * 获取到总页数
	 * @return
	 */
	public int getMaxPage() {
		return this.total % this.rows == 0 ? 
				this.total / this.rows : 
					(this.total / this.rows) + 1;
	}
	
	/**
	 * 获取下一页页码
	 * @return
	 */
	public int getNextPage() {
		return this.page < this.getMaxPage() ? this.page+1 : this.page;
	}
	
	/**
	 * 获取上一页页码
	 * @return
	 */
	public int getPreviousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}

}

创建子控制器

BookAction

package web;

import java.sql.SQLException;
import java.util.List;

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


import com.liuting.framework.ActionSupport;
import com.liuting.framework.ModelDriven;

import dao.BookDao;
import entity.Book;
import util.PageBean;

public class BookAction extends ActionSupport implements ModelDriven{
	
	private BookDao bookDao=new BookDao();
	private Book book=new Book();
	
	
   /**
    * 查询分页的数据
    * @param req
    * @param resp
    * @return
    */
	public String list(HttpServletRequest req,HttpServletResponse resp) {
		try {
			PageBean pageBean=new PageBean();
			pageBean.setRequest(req);
			List list = this.bookDao.list(book, pageBean);
			req.setAttribute("bookList", list);
			req.setAttribute("pageBean", pageBean);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "list";
	}

	
	/**
	 * 增加书籍
	 * @param req
	 * @param resp
	 * @return
	 */
	public String add(HttpServletRequest req,HttpServletResponse resp) {
		try {
			int n = this.bookDao.add(book);
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}
	
	
	/**
	 * 删除书籍
	 * @param req
	 * @param resp
	 * @return
	 */
	
	public String delete(HttpServletRequest req,HttpServletResponse resp) {
		try {
			int n = this.bookDao.delete(book);
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}
	
	/**
	 * 加载当前所需要修改的书籍信息
	 * @param req
	 * @param resp
	 * @return
	 */
	public String load(HttpServletRequest req,HttpServletResponse resp) {
		try {
			List list=this.bookDao.list(book, null);
			req.setAttribute("book", list.get(0));
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toEdit";
	}
	
	
	
	/**
	 * 开始修改书籍信息
	 * @param req
	 * @param resp
	 * @return
	 */

	public String update(HttpServletRequest req,HttpServletResponse resp)  {
		try {
			int n = this.bookDao.update(book);
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	}

	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return book;
	}
	
	
	

}

配置XML

web.xml



  mvc_curd
   
  			encodingFiter
            util.EncodingFiter
  
  
            encodingFiter
            /*
  
  
   
   			dispatherServlet
            com.framework.DispatherServlet 
            
                      xmlPath
                      /mvc.xml
            
   
   
   		dispatherServlet
        *.action
   
      

mvc.xml




	
	
		
		
		
	
	
	

jsp页面内容

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
    <%@ taglib uri="/zking" prefix="z" %>




Insert title here



小说目录

书名:
编号 名称 价格 操作
${b.bid } ${b.bname } ${b.price }    
${pageBean}

自定义MV3_第4张图片

修改和增加页面

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




Insert title here



	
编号:
书名:
价格:

自定义MV3_第5张图片

最后进行测试,这样我们的自定义mvc模式就完成了

你可能感兴趣的:(自定义MVC3)