使用自定义mvc框架完成CRUD操作
1、通用分页的jar、自定义mvc框架、自定义标签
导入jar、导入之前写好的pageTag、自定义mvc.xml
1.1导入需要用到的jar包
1.2导入之前已写好的所有辅助类(可在前面写的mvc博客参考)
1.3优化BaseDao
1 package com.util; 2 3 import java.lang.reflect.Field; 4 import java.sql.Connection; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.util.ArrayList; 9 import java.util.List; 10 11 import com.sun.corba.se.spi.legacy.connection.GetEndPointInfoAgainException; 12 import com.entity.Book; 13 14 /** 15 * 代表你要对哪个实体类对应的表进行分页查询 16 * @author ** 17 * 18 * @param <T> 19 */ 20 public class BaseDao<T> { 21 22 /** 23 * 24 * @param sql 查询不同的实体类,对应的sql语句不同所以需要传递 25 * @param clz 生产出不同的实体类对应的实列,然后装进list容器中返回 26 * @param pageBean 决定是否分页 27 * @return 28 * @throws SQLException 29 * @throws IllegalAccessException 30 * @throws InstantiationException 31 */ 32 public List<T> executeQuery(String sql,Class clz,PageBean pageBean)throws SQLException, InstantiationException, IllegalAccessException { 33 Connection con = DBAccess.getConnection(); 34 PreparedStatement ps =null; 35 ResultSet rs = null; 36 37 if(pageBean!=null && pageBean.isPagination()) { 38 //需要分页 39 //计算总记录数 40 String consql= getCountsql(sql); 41 ps = con.prepareStatement(consql); 42 rs=ps.executeQuery(); 43 if(rs.next()) { 44 pageBean.setTotal(rs.getLong(1)+""); 45 } 46 //查询出符合条件的结果集 47 String pagesql = getPageSql(sql,pageBean); 48 ps = con.prepareStatement(pagesql); 49 rs = ps.executeQuery(); 50 51 52 }else { 53 ps = con.prepareStatement(sql); 54 rs = ps.executeQuery(); 55 } 56 List<T> list= new ArrayList<>(); 57 T t; 58 while(rs.next()) { 59 /** 60 *1、实例化一个book对象(该对象为空) 61 *2、取book的所有属性,然后给器赋值 62 * 2.1获取所有属性对象 63 * 2.2给属性赋值 64 *3、赋值之后的book对象装进list容器中 65 */ 66 // list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price"))); 67 68 t =(T) clz.newInstance(); 69 Field[] fields = clz.getDeclaredFields(); 70 for (Field field : fields) { 71 field.setAccessible(true); 72 field.set(t, rs.getObject(field.getName())); 73 } 74 list.add(t); 75 } 76 DBAccess.close(con, ps, rs); 77 return list; 78 79 } 80 81 /** 82 * 利用原生sql拼接出符合条件的结果集的查询sql 83 * @param sql 84 * @param pageBean 85 * @return 86 */ 87 private String getPageSql(String sql, PageBean pageBean) { 88 // TODO Auto-generated method stub 89 return sql+" LIMIT "+pageBean.getStartIndex()+","+pageBean.getRows()+""; 90 } 91 92 /** 93 * 94 * @param sql 95 * @return 96 */ 97 private String getCountsql(String sql) { 98 99 return "SELECT COUNT(1) FROM ("+sql+")t"; 100 } 101 102 /** 103 * 通用的增删改方法 104 * @param sql 决定增删改的一种 105 * @param attrs 决定?的位置 new String[]{"bid","bname","price"} 106 * @param t 要操作的实体类 107 * @return 108 * @throws SQLException 109 * @throws IllegalAccessException 110 * @throws IllegalArgumentException 111 * @throws SecurityException 112 * @throws NoSuchFieldException 113 */ 114 public int executeUpdate(String sql,String[] attrs,T t) throws SQLException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException{ 115 Connection con = DBAccess.getConnection(); 116 PreparedStatement ps = con.prepareStatement(sql); 117 // ps.setString(2, book.getBname()); 118 // ps.setFloat(3, book.getPrice()); 119 // ps.setInt(1, book.getBid()); 120 121 for (int i = 1; i <= attrs.length; i++) { 122 Field f = t.getClass().getDeclaredField(attrs[i-1]); 123 f.setAccessible(true); 124 ps.setObject(i, f.get(t)); 125 } 126 int num = ps.executeUpdate(); 127 128 return num; 129 } 130 131 132 133 }
1.4配置mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?> <config> <!-- <action path="/addCal" type="com.yuan.web.AddCalAction"> <forward name="res" path="/res.jsp" redirect="false" /> </action> <action path="/delCal" type="com.yuan.web.DelCalAction"> <forward name="res" path="/res.jsp" redirect="true"/> </action> --> <action path="/cal" type="com.yuan.web.CalAction"> <forward name="res" path="/res.jsp" redirect="false"/> </action> <action path="/book" type="com.yuan.web.BookAction"> <forward name="list" path="/bookList.jsp" redirect="false"/> <forward name="edit" path="/bookEdit.jsp" redirect="false"/> <!-- 增删改一定要用重定向,查询用转发, --> <forward name="toList" path="/book.action?methodName=list"/> </action> </config>
注:在这里需要注意forward标签里面的redirect,当值为false时为重定向,为true或者不填则是转发,
配置的时候增删改一定要用重定向,查询用转发,否则会出现小bug!!!!
2、dao层 通用的增删改方法
2.1新建一个BookDao
1 package com.dao; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.SQLException; 6 import java.util.List; 7 8 import com.entity.Book; 9 import com.util.BaseDao; 10 import com.util.DBAccess; 11 import com.util.PageBean; 12 import com.util.StringUtils; 13 14 public class BookDao extends BaseDao<Book> { 15 16 public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{ 17 String sql = "SELECT * FROM t_mvc_book WHERE TRUE "; 18 String bname=book.getBname(); 19 int bid=book.getBid(); 20 if(StringUtils.isNotBlank(bname)) { 21 sql+=" AND bname like '%"+bname+"%'";//注意拼接的时候一定要记得在前面打一个空格 22 } 23 if(bid != 0) { 24 sql+= " AND bid ="+bid; 25 } 26 System.out.println(sql); 27 return super.executeQuery(sql, Book.class, pageBean); 28 } 29 30 /** 31 * 修改方法 32 */ 33 public int edit (Book book) throws SQLException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { 34 String sql="UPDATE t_mvc_book SET bname=?,price=? WHERE bid=?"; 35 return super.executeUpdate(sql, new String[] {"bname","price","bid"}, book); 36 } 37 /** 38 * 新增方法 39 */ 40 public int add(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { 41 String sql = "INSERT INTO t_mvc_book VALUES(?,?,?)"; 42 System.out.println(sql); 43 return super.executeUpdate(sql, new String[] {"bid","bname","price"}, book); 44 } 45 46 /** 47 * 删除方法 48 */ 49 public int del(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { 50 String sql = "DELETE FROM t_mvc_book WHERE bid=?"; 51 return super.executeUpdate(sql, new String[] {"bid"}, book); 52 } 53 54 55 56 }
2.2新建一个与数据库数据匹配的实体类Book
1 package com.entity; 2 3 public class Book { 4 5 private int bid; 6 private String bname; 7 private float price; 8 public int getBid() { 9 return bid; 10 } 11 public void setBid(int bid) { 12 this.bid = bid; 13 } 14 public String getBname() { 15 return bname; 16 } 17 public void setBname(String bname) { 18 this.bname = bname; 19 } 20 public float getPrice() { 21 return price; 22 } 23 public void setPrice(float price) { 24 this.price = price; 25 } 26 @Override 27 public String toString() { 28 return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; 29 } 30 31 32 }
3、web层
3.1新建BookAction 继承上次写的优化后的子控制器并且实现(implement)ModelDrivern模型驱动接口
1 package com.yuan.web; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import com.dao.BookDao; 10 import com.entity.Book; 11 import com.util.PageBean; 12 import com.yuan.framework.ActionSupport; 13 import com.yuan.framework.ModelDrivern; 14 15 16 /** 17 * 分页查询 18 * @author ** 19 * 20 */ 21 public class BookAction extends ActionSupport implements ModelDrivern<Book> { 22 23 private Book book = new Book(); 24 private BookDao bookDao = new BookDao(); 25 26 27 public String list(HttpServletRequest req, HttpServletResponse resp) { 28 PageBean bean = new PageBean(); 29 bean.setRequest(req); 30 try { 31 List<Book> list = this.bookDao.list(book, bean); 32 req.setAttribute("booklist", list); 33 req.setAttribute("pageBean", bean); 34 } catch (InstantiationException | IllegalAccessException | SQLException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 } 38 39 return "list"; 40 } 41 42 /** 43 * 跳转到增加或者修改页面 44 * @param req 45 * @param resp 46 * @return 47 */ 48 public String preSave(HttpServletRequest req, HttpServletResponse resp) { 49 //bid的类型是int类型 int类型的默认值是0,如果jsp未传递bid的参数值,那么bid=0;跳转新增,否则跳转修改。 50 if(book.getBid() == 0) { 51 System.out.println("增加...."); 52 }else { 53 //修改数据后回显 54 try { 55 Book b = this.bookDao.list(book, null).get(0); 56 req.setAttribute("book", b); 57 } catch (InstantiationException | IllegalAccessException | SQLException e) { 58 e.printStackTrace(); 59 } 60 } 61 62 return "edit"; 63 } 64 65 /** 66 * 新增 67 * @param req 68 * @param resp 69 * @return 70 */ 71 public String add(HttpServletRequest req, HttpServletResponse resp) { 72 try { 73 this.bookDao.add(book); 74 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 75 | SQLException e) { 76 // TODO Auto-generated catch block 77 e.printStackTrace(); 78 } 79 //新增完之后需要刷新页面 80 return "toList"; 81 } 82 /** 83 * 修改 84 * @param req 85 * @param resp 86 * @return 87 */ 88 public String edit(HttpServletRequest req, HttpServletResponse resp) { 89 try { 90 this.bookDao.edit(book); 91 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 92 | SQLException e) { 93 // TODO Auto-generated catch block 94 e.printStackTrace(); 95 } 96 //修改之后需要刷新页面 97 return "toList"; 98 } 99 100 /** 101 * 删除 102 * @param req 103 * @param resp 104 * @return 105 */ 106 public String del(HttpServletRequest req, HttpServletResponse resp) { 107 try { 108 this.bookDao.del(book); 109 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException 110 | SQLException e) { 111 // TODO Auto-generated catch block 112 e.printStackTrace(); 113 } 114 //删除之后需要刷新页面 115 return "toList"; 116 } 117 118 119 @Override 120 public Book getModel() { 121 // TODO Auto-generated method stub 122 return book; 123 } 124 125 126 }
4、jsp页面
4.1数据展示首页booklist
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page isELIgnored="false"%> 4 <%@taglib prefix="z" uri="/yuan" %> 5 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 7 <html> 8 <head> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 10 <title>Insert title here</title> 11 </head> 12 <body> 13 <%-- <c:if test="${empty bookList }"> 14 <jsp:forward page="bookServlet.action"></jsp:forward> 15 </c:if> --%> 16 <h2>小说目录</h2> 17 <br> 18 <form action="${pageContext.request.contextPath}/book.action?methodName=list" 19 method="post"> 20 书名:<input type="text" name="bname"> <input type="submit" 21 value="确定"> 22 <input type="hidden" name="pagination" value="false"> 23 <input type="hidden" name="rows" value="20"> 24 </form> 25 <a href="${pageContext.request.contextPath}/book.action?methodName=preSave">新增</a> 26 <table border="1" width="100%"> 27 <tr> 28 <td>编号</td> 29 <td>名称</td> 30 <td>价格</td> 31 <td>操作</td> 32 </tr> 33 <c:forEach items="${booklist }" var="s"> 34 <tr> 35 <td>${s.bid }</td> 36 <td>${s.bname }</td> 37 <td>${s.price}</td> 38 <td> 39 <a href="${pageContext.request.contextPath}/book.action?methodName=preSave&&bid=${s.bid }">修改</a> 40 <a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${s.bid }">删除</a> 41 </td> 42 </tr> 43 </c:forEach> 44 </table> 45 <z:Page pageBean="${pageBean }"></z:Page> 46 47 </body> 48 </html>
4.2新增和修改的页面
因为我们在web层做了判断,判别出是新增还是修改,所以不需要担心只有一个界面的问题
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="${pageContext.request.contextPath}/book.action" method="post"> 11 <input type="hidden" name="methodName" value="${book.bname==null ? 'add' : 'edit' }"> 12 书籍ID:<input type="text" name="bid" value="${book.bid }"><br> 13 书籍名称:<input type="text" name="bname" value="${book.bname }"><br> 14 书籍价格:<input type="text" name="price" value="${book.price }"><br> 15 <input type="submit"> 16 </form> 17 </body> 18 </html>
5、结果展示
5.1新增(查询)
5.2修改
5.3删除
谢谢观看^-^!!!