mvc增删改查
导入需要的工具类自定义mvc(一),通用分页(二)
导入需要导入的jar包:
bookDao:
package com.wangjing.web;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import com.wangjing.entity.Book;
import com.wangjing.util.BaseDao;
import com.wangjing.util.DBAccess;
import com.wangjing.util.PageBean;
import com.wangjing.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book,PageBean pageBean) throws Exception{
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 b) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, b, new String [] {"bid","bname","price"});
}
public int edit(Book b) throws Exception {
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, b, new String [] {"bname","price","bid"});
}
public int del(Book b) throws Exception {
String sql = "delete from t_mvc_book where bid = ?";
return super.executeUpdate(sql, b, new String [] {"bid"});
}
public static void main(String[] args) throws Exception {
BookDao bookDao = new BookDao();
Book book = new Book(141313,"xxx",56f);
bookDao.del(book);
}
}
BaseDao:
package com.wangjing.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.wangjing.util.DBAccess;
import com.wangjing.util.PageBean;
/**
* 用来处理所用的增删改查
* @author wj
*
* @param <T>
*/
public class BaseDao<T> {
/**
* @param sql 可能不同的表,那么意味着SQL是变化的,那么它是从子类处理再传递到父类
* @param clz 需要返回不同的对象集合 Book.class/Oreder.class
* @param pageBean 可能要分页
* @return
* @throws Exception
*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws Exception{
List<T> list=new ArrayList<>();
Connection con=DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
if(pageBean !=null && pageBean.isPagination()) {
// 分页代码
/**
* 1.分页是与pagebaen中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());
}
String pagetSql = getpageSql(sql,pageBean);
pst= con.prepareStatement(pagetSql);
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 t 实体类(里面包含了参数值)
* @param attrs 代表SQL语句的问号
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int executeUpdate(String sql,T t,String [] attrs) throws IllegalArgumentException, IllegalAccessException, SQLException {
Connection con = DBAccess.getConnection();
PreparedStatement ps= con.prepareStatement(sql);
Field field = null;
for (int i = 0; i < attrs.length; i++) {
try {
field = t.getClass().getDeclaredField(attrs[i]);
field.setAccessible(true);
ps.setObject(i+1, field.get(t));
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int num = ps.executeUpdate();
DBAccess.close(con, ps, null);
return num;
}
}
BookAction :
package com.wangjing.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wangjing.entity.Book;
import com.wangjing.framework.ActionSupport;
import com.wangjing.framework.ModeDriven;
import com.wangjing.util.PageBean;
public class BookAction extends ActionSupport implements ModeDriven<Book>{
private Book book = new Book();
private BookDao bookDao = new BookDao();
public String list(HttpServletRequest req,HttpServletResponse resp) throws Exception {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Book> list = this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pageBean", pageBean);
return "list";
}
/**
* 跳转新增修改页面(新增修改是同一个)
* @param req
* @param resp
* @return
*/
public String preSave(HttpServletRequest req,HttpServletResponse resp) {
if(book.getBid() != 0) {
try {
// 数据回显的数据
Book b = this.bookDao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "edit";
}
/**
* 增加
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 修改
* @param req
* @param resp
* @return
*/
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 删除
* @param req
* @param resp
* @return
*/
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.del(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel() {
// TODO Auto-generated method stub
return book;
}
}
bookList 主页:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="w" uri="/wangjing" %>
<!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>
</head>
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/book.action?methodName=list"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<a href="${pageContext.request.contextPath}/book.action?methodName=preSave">新增</a>
<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>
<a href="${pageContext.request.contextPath}/book.action?methodName=preSave&&bid=${b.bid}">修改</a>
<a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<w:page pageBean="${pageBean}"></w:page>
</body>
</html>
bookEdit 增加修改页面:
<%@ 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>
</head>
<body>
<form action="${pageContext.request.contextPath}/book.action?methodName=${book.bname == null ? 'add' : 'edit'}" method="post">
bid:<input type="text" value="${book.bid}" name="bid">
bname:<input type="text" value="${book.bname}" name="bname">
price:<input type="text" value="${book.price}" name="price">
<input type="submit" value="ok">
</form>
</body>
</html>
mvc.xml :
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.wangjing.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>
增加:
修改:
删除: