自定义MVC框架的增删改查
对上一次的进行优化:
整个项目:
jar包;
提取jar包链接:https://pan.baidu.com/s/1A84IZ_SQIRvLqU_mx1WSFA
提取码:r248
- 通用的分页查询
BaseDao:
package com.su.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 com.su.entity.Book;
/**
* 用来处理所有表的通用的增删改查的基类
*
* 查询指的是:通用的分页查询
* @author Administrator
*
* @param <T>
*/
public class BaseDao<T> {
/**
*
* @param sql 可能不同的表,那么意味着sql是变化的,那么它是从子类处理好再传递到父类
* @param clz 需要返回不同的对象集合 Book.class/Order.class
* @param pageBean 可能要分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
List<T> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
if(pageBean != null && pageBean.isPagination()) {
// 分页代码
/*
* 1、分页是与pagebean中total,意味着需要查询数据库得到total赋值给pagebean
* 2、查询出符合条件的某一页的数据
*/
// select count(*) from (select * from t_mvc_book where bname like '%圣墟%') t;
String countSql = getCountSql(sql);
pst = con.prepareStatement(countSql);
rs = pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getObject(1).toString());
}
// select * from t_mvc_book where bname like '%圣墟%' limit 20,10
String pageSql = getPageSql(sql,pageBean);
pst = con.prepareStatement(pageSql);
rs = pst.executeQuery();
}else {
// 不分页代码
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
}
T t = null;
while(rs.next()) {
t = (T) clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
DBAccess.close(con, pst, rs);
return list;
}
private String getPageSql(String sql, PageBean pageBean) {
return sql + "limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getCountSql(String sql) {
return "select count(1) from ("+sql+") t";
}
/**
*
* @param sql 增删改的sql语句
* @param attrs 代表了sql语句中的问号 "bname","price","bid"
* @param t 实体类(里面包含了参数值)
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int executeUpdate(String sql,String[] attrs,T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
Field field = null;
for (int i = 0; i < attrs.length; i++) {
try {
field = t.getClass().getDeclaredField(attrs[i]);
field.setAccessible(true);
pst.setObject(i+1, field.get(t));
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
}
int num = pst.executeUpdate();
DBAccess.close(con, pst, null);
return num;
}
}
- 继承通用BaseDao方法
BookDao:
package su;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.su.entity.Book;
import com.su.util.BaseDao;
import com.su.util.PageBean;
import com.su.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_mvc_book where true ";
String bname = book.getBname();
int bid = book.getBid();
if(StringUtils.isNotBlank(bname)) {
sql += " and bname like '%"+bname+"%'";
}
if(bid != 0 ) {
sql += " and bid = "+bid;
}
return super.executeQuery(sql, Book.class, pageBean);
}
public int add(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, new String[] {"bid","bname","price"}, book);
}
public int edit(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, new String[] {"bname","price","bid"}, book);
}
public int del(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql = "delete from t_mvc_book where bid = ?";
return super.executeUpdate(sql, new String[] {"bid"}, book);
}
public static void main(String[] args) {
BookDao bookDao = new BookDao();
Book book = new Book(141313, "xxx", 56f);
try {
bookDao.del(book);
} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
}
- 通用分页
PageBean:
package com.su.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<String, String[]> 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<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> 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 com.su.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.su.entity.Book;
import com.su.framework.ActionSupport;
import com.su.framework.ModelDriven;
import com.su.util.PageBean;
import su.BookDao;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
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<Book> 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 (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.del(book);
} 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<Book> 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:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>mvc_curd</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatherServlet</servlet-name>
<servlet-class>com.framework.DispatherServlet </servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
mvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/bookAction" type="web.BookAction">
<forward name="list" path="/book.jsp" redirect="false" />
<forward name="toList" path="bookAction.action?methodName=list" redirect="true" />
<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
</action>
</config>
- 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function add(){
window.location.href="bookEdit.jsp";
}
function update(bid){
window.location.href="${pageContext.request.contextPath}/bookAction.action?methodName=load&&bid="+bid;
}
function del(bid){
window.location.href="${pageContext.request.contextPath}/bookAction.action?methodName=delete&&bid="+bid;
}
</script>
</head>
<body>
<h2>小说目录</h2>
<form action="${pageContext.request.contextPath}/bookAction.action?methodName=list"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<button onclick="add();">新增</button>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
<c:forEach items="${bookList }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<button onclick="update(${b.bid });">修改</button>
<button onclick="del(${b.bid });">删除</button>
</td>
</tr>
</c:forEach>
</table>
${pageBean}
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
- 删除和增加界面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function doSubmit(bid){
var bookForm =document.getElementById("bookForm");
if(bid){
//修改时执行
bookForm.action='${pageContext.request.contextPath}/bookAction.action?methodName=update';
}else{
//新增时候执行
bookForm.action='${pageContext.request.contextPath}/bookAction.action?methodName=add';
}
bookForm.submit();
}
</script>
</head>
<body>
<form id="bookForm" method="post" action="${pageContext.request.contextPath}/bookAction.action?methodName=list">
编号:<input name="bid" value="${book.bid }"><br>
书名:<input name="bname" value="${book.bname }"><br>
价格:<input name="price" value="${book.price }"><br>
<input type="submit" value="提交" onclick="doSubmit('${book.bid }');"><br>
</form>
</body>
</html>