通用增删改查
在实现一些功能的时候我们发现有些代码要重复很多遍,那么就显得代码很臃肿,并且还重复许多相同的代码,所以就有了通用的增删改查:
我们对书本进行增删改查,先建一个关于书籍的实体类:
我们把以前写过的代码打成jar包,然后导入进项目里面:
不知道的,可以去看我以前的代码
package com.wt.entity;
public class Book {
private int bid;
private String bname;
private float price;
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
super();
}
}
咱们要在BaseDao里面写一个关于通用增删改查的方法:
/**
* 通用的增删改方法
* @param t 增删改的那个类的名字
* @param sql 增删改的sql语句
* @param attrs ?所代表的实体类的属性
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int executeUpdate(T t,String sql,String[] attrs) 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();
}
其次我们就可以写dao方法了,要让BookDao继承BaseDao:
package com.wt.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.wt.entity.Book;
import com.wt.util.BaseDao;
import com.wt.util.DBAccess;
import com.wt.util.PageBean;
import com.wt.util.StringUtils;
public class BookDao extends BaseDao<Book>{
public List<Book> ls(Book bk,PageBean pb) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_mvc_book where true";
if(StringUtils.isNotBlank(bk.getBname())) {
sql +=" and banme like '%"+bk.getBname()+"%'";
}
return super.executeQuery(sql, Book.class, pb);
}
/**
* 增加
* @param bk 对book类进行操作
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int add(Book bk) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String sql ="insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(bk, sql, new String[] {"bid","bname","price"});
}
/**
* 删除
* @param bk
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int del(Book bk) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String sql ="delete from t_mvc_book where bid=?";
return super.executeUpdate(bk, sql, new String[] {"bid"});
}
/**
* 修改
* @param bk
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int update(Book bk) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String sql ="update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(bk, sql, new String[] {"bname","price","bid"});
}
}
接下来我们就可以写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">
<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=del&&bid="+bid;
}
</script>
<title>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
<%=System.currentTimeMillis() %>
<br>
<form action="${pageContext.request.contextPath}/bookAction.action?methodName=ls"
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>
<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" action="${pageContext.request.contextPath}/bookAction.action?methodName=ls" method="post">
bid:<input type="text" name="bid" value="${book.bid }"><br>
bname:<input type="text" name="bname" value="${book.bname }"><br>
price:<input type="text" name="price" value="${book.price }"><br>
<input type="submit" value="提交" onclick="doSubmit('${book.bid }');"><br>
</form>
</body>
</html>
接下来就去我们的自己写的xml文件里面:
<action path="/bookAction" type="com.wt.web.BookAction">
<forward name="list" path="/booklist.jsp" redirect="false" />
<forward name="toList" path="bookAction.action?methodName=ls" redirect="true" />
<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
</action>
我们要在子控制器种接收这些值并且实行增删查改的方法
package com.wt.web;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wt.dao.BookDao;
import com.wt.entity.Book;
import com.wt.util.PageBean;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriven;
/**
* 增删改查子控制器
* @author MRCHENIKE
*
*/
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private BookDao bd = new BookDao();
private Book bk = new Book();
/**
* 查询数据分页的展示
* @param req
* @param resp
* @return
*/
public String ls(HttpServletRequest req,HttpServletResponse resp) {
try {
PageBean pb = new PageBean();
pb.setRequest(req);
List<Book> ls = this.bd.ls(bk, pb);
req.setAttribute("bookList", ls);
req.setAttribute("pageBean", pb);
System.out.println(ls.size());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return "list";
}
/**
* 增加书籍
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bd.add(bk);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return "toList";
}
/**
* 删除书籍
* @param req
* @param resp
* @return
*/
public String del(HttpServletRequest req,HttpServletResponse resp) {
bk.setBid(25000);
try {
this.bd.del(bk);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return "toList";
}
/**
* 加载需要修改的数据
* @param req
* @param resp
* @return
*/
public String load(HttpServletRequest req,HttpServletResponse resp) {
try {
List<Book> ls = this.bd.ls(bk, null);
req.setAttribute("book", ls.get(0));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return "toEdit";
}
/**
* 开始修改书籍信息
* @param req
* @param resp
* @return
*/
public String update(HttpServletRequest req,HttpServletResponse resp) {
try {
int reCode = this.bd.update(bk);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel(HttpServletRequest arg0) throws IllegalAccessException, InvocationTargetException {
return bk;
}
}
然后我们就可以配置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_crud</display-name>
<!--过滤编码格式 -->
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.wt.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>com.zking.framework.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
修改界面:
总结:增/删/改用重定向,查询用转发,代码的话,最重要的还是思路,所以我们不能死记代码,要弄清楚代码的原理以及思路。