t_mvc_book 表的增删改查
1、通用分页的jar、自定义mvc框架、自定义标签
导入jar、导入之前写好的pageTag、自定义mvc.xml
2、dao层 通用的增删改方法
BaseDao
package com.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;
/**
* 用来处理所有的表的通用的增删改查的基类
*
* @author 17628
*
*/
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 Exception {
List<T> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
if(pagebean !=null && pagebean.isPagination()) {
// 分页代码
/*
* 1、分页是与pagebean中total,意味真需要查询数据库得到total赋值给pagebean
* 2、查询出符合条件的某一页的数据
*/
String countSql=getCountSql(sql);
ps=con.prepareStatement(countSql);
rs=ps.executeQuery();
if(rs.next()) {
pagebean.setTotal(rs.getInt(1));
}
// 进行拼接
String pageSql=getPageSql(sql,pagebean);
ps = con.prepareStatement(pageSql);
rs =ps.executeQuery();
}else {
ps = con.prepareStatement(sql);
rs =ps.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, ps, 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语句中的问号
* @param t 实体类 (里面包含参数值)
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int execute(String sql,String[] attrs, T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
Connection con=DBAccess.getConnection();
PreparedStatement ps=con.prepareStatement(sql);
// ps.setInt(1, book.getBid());
// ps.setString(2, book.getBname());
// ps.setFloat(3, book.getPrice());
Field[] fields=t.getClass().getDeclaredFields();
for (int i = 0; i < attrs.length; i++) {
fields[i].setAccessible(true);
ps.setObject(i+1,fields[i].get(t));
}
int num=ps.executeUpdate();
DBAccess.close(con, ps, null);
return num;
}
}
BookDao(继承 BaseDao)
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.entity.Book;
import com.util.BaseDao;
import com.util.DBAccess;
import com.util.PageBean;
import com.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 book) throws Exception {
String sql="insert into t_mvc_book values(?,?,?)";
return super.execute(sql, new String[] {"bid","bname","price"}, book);
}
public int edit(Book book) throws Exception {
String sql=" update t_mvc_book set bname=?, price=? where bid=?";
return super.execute(sql, new String[] {"bname,price,bid"}, book);
}
public int del(Book book) throws Exception {
String sql=" delete from t_mvc_book where bid=?";
return super.execute(sql, new String[] {"bid"}, book);
}
public static void main(String[] args) {
BookDao bookDao=new BookDao();
Book book=new Book(141313, "xxx", 56f);
try {
//bookDao.add(book);
bookDao.del(book);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、web层(BookAction)
package com.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.BookDao;
import com.entity.Book;
import com.framewrok.ActionSuppot;
import com.framewrok.ModelDriver;
import com.util.PageBean;
public class BookAction extends ActionSuppot implements ModelDriver<Book>{
private Book book=new Book();
private BookDao bookDao=new BookDao();
public String list(HttpServletRequest req,HttpServletResponse resp) {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
try {
List<Book> list=this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pageBean", pageBean);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
/**
* 调转新增修改页面(新增修改页面是同一个)
* @param req
* @param resp
* @return
*/
public String preSave(HttpServletRequest req,HttpServletResponse resp) {
if(book.getBid() !=0) {
//System.out.println("新增页面不作任何操作");
try {
Book b= this.bookDao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (Exception e) {
e.printStackTrace();
}
}
return "edit";
}
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.add(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.del(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel() {
return book;
}
}
【注意】
增/删/改用重定向,查询用转发
这样做的目的是 阻止多次上传请求带来数据重复的影响
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.caoguangli.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>
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>web_mvc</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.caoguangli.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.caoguangli.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>xmlPath</param-name>
<param-value>/mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
4、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="/cbw" prefix="b"%>
<!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">
<!--用户设置查询 一页20条记录 -->
<!-- <input type="hidden" name="rows" value="20"/> -->
<!--用户设置不分页 -->
<!-- <input type="hidden" name="pagination" value="false"/> -->
书名:<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">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
<h:page pageBean="${pagebean}"></h:page>
</html>
bookEdit.jsp
<%@ 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>书籍的编辑页面</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"><br>
bname:<input type="text" value="${book.bname}" name="bname"><br>
price:<input type="text" value="${book.price}" name="price"><br>
<input type="submit" value="提交">
</form>
</body>
</html>