这次我们来实现对表的增删改查的最终优化。
mvc.jar
将之前的写好的加强自定义框架打包成一个jar包,将mvc.jar导入项目中。
BaseDao
public class BaseDao<T> {
private static final String T = null;
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
public List<T> executeQuery(String sql,Class clz,PageBean pagebean) throws InstantiationException, IllegalAccessException, SQLException{
List<T> 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();
}
}
BookDao,继承BaseDao
package com.shl.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.mysql.jdbc.StringUtils;
import com.shl.entity.Book;
import com.shl.util.BaseDao;
import com.shl.util.DBAccess;
import com.shl.util.PageBean;
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";
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);
}
}
子控制器BookAction
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 (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<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;
}
}
mvc.xml
这里我们需要特别注意的就是,我们查询要用转发,增删改用重定向,因为如果我们增删改用转发的话,刷新页面时会造成重复提交。
<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>
web.xml
<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.shl.framework.DispatherServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
bookList.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="/shl" prefix="s" %>
<!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>
</body>
</html>
bookEdit.jsp
<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">
bid:<input name="bid" value="${book.bid }"><br>
bname:<input name="bname" value="${book.bname }"><br>
price:<input name="price" value="${book.price }"><br>
<input type="submit" value="提交" onclick="doSubmit();"><br>
</form>
</body>
这样我们的自定义MVC的增删查改已经完成好了。