原理:利用我们上次写好的自定义框架,把它打成jar包导入,进行对书本的增删查改的操作。利用转发和重定向在控制器内部跳转避免重复提交数据。
BaseDao
package com.xy.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class BaseDao<T> {
public static interface CallBack<E>{
//遍历ResultSet结果集
public List<E> forEach(ResultSet rs) throws SQLException;
}
/**
* 分页查询
* @param sql 普通的sql
* @param pageBean
* @return
*/
public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack){
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=DBHelper.getConnection();
//判断是否分页
if(null!=pageBean&&pageBean.isPagination()) {
//第一次查询总记录数
String countSql=this.getCountSql(sql);
stmt=conn.prepareStatement(countSql);
rs=stmt.executeQuery();
if(rs.next()) {
Object obj = rs.getObject(1);
pageBean.setTotal(Integer.parseInt(obj.toString()));
}
//DBHelper.close(conn, stmt, rs);
//第二次满足条件的分页数据集
sql=this.getPagerSql(sql, pageBean);
}
stmt=conn.prepareStatement(sql);
rs=stmt.executeQuery();
//处理结果集
return callBack.forEach(rs);
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.close(conn, stmt, rs);
}
return null;
}
/**
* 将普通的Sql语句转换成查总记录数的Sql语句
* 例如:sql=="select * from t_book where bookname='123'"
* @param sql
* @return
*/
private String getCountSql(String sql) {
return "select count(1) from ("+sql+") t1";
}
/**
* 将普通Sql语句转换成查询分页的Sql语句
* 例如:sql=="select * from t_book where bookname='123'"
* @param sql
* @param pageBean
* @return
*/
private String getPagerSql(String sql,PageBean pageBean) {
return sql+" Limit "+pageBean.getStartIndex()+","+
pageBean.getRows();
}
}
BookAction
package com.xy.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;
import com.util.PageBean;
import com.xy.dao.BookDao;
import com.xy.entity.Book;
import com.xy.framework.DispatcherServlet;
import com.xy.framework.ModelDriver;
public class BookAction extends DispatcherServlet implements ModelDriver<Book> {
private Book book=new Book();
private BookDao bookDao=new BookDao();
@Override
public Book getModel() {
return book;
}
/**
* 书本新增
* @param req
* @param resp
* @return
* @throws SerialException
* @throws IOException
*/
public String addBook(HttpServletRequest req,HttpServletResponse resp)throws SerialException,IOException {
bookDao.addBook(book);
// bookAction.action?menthodName=queryBookPager
req.getSession().setAttribute("message", "新增书本信息成功");
return "success";
}
/**
* 删除
* @param req
* @param resp
* @return
* @throws SerialException
* @throws IOException
*/
public String delBook(HttpServletRequest req,HttpServletResponse resp)throws SerialException,IOException {
bookDao.delBook(book);
req.getSession().setAttribute("message", "删除书本信息成功");
return "success";
}
/**
* 修改
* @param req
* @param resp
* @return
* @throws SerialException
* @throws IOException
*/
public String editBook(HttpServletRequest req,HttpServletResponse resp)throws SerialException,IOException {
bookDao.editBook(book);
req.getSession().setAttribute("message", "修改书本信息成功");
return "success";
}
/**
* 查所有
* @param req
* @param resp
* @return
* @throws SerialException
* @throws IOException
*/
public String queryBookPager(HttpServletRequest req,HttpServletResponse resp)throws SerialException,IOException {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Book> books = bookDao.queryBookPager(book, pageBean);
req.setAttribute("books", books);
req.setAttribute("pageBean", pageBean);
return "success";
}
/**
* 查单个
* @param req
* @param resp
* @return
* @throws SerialException
* @throws IOException
*/
public String querySingleBook(HttpServletRequest req,HttpServletResponse resp)throws SerialException,IOException {
Book b=bookDao.querySingleBook(book);
req.setAttribute("book", b);
//定义类型参数,告知去哪里,修改页面,详情页面
String type=req.getParameter("type");
if("edit".equals(type)) {
return "edit";
}
else {
return "detail";
}
}
}
Book
package com.xy.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();
}
}
BookDao
package com.xy.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.util.BaseDao;
import com.util.PageBean;
import com.util.StringUtils;
import com.xy.entity.Book;
import com.xy.util.BaseDao.CallBack;
import com.xy.util.CommonUtils;
import com.xy.util.DBHelper;
public class BookDao extends BaseDao<Book>{
public void addBook(Book book) {
String sql="insert into t_mvc_book";
Connection con=null;
PreparedStatement ps=null;
try {
con=DBHelper.getConnection();
ps=con.prepareStatement(sql);
ps.setInt(1, book.getBid());
ps.setString(2, book.getBname());
ps.setFloat(3, book.getPrice());
ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.close(con, ps, null);
}
}
public void editBook(Book book) {
String sql="update tb_t_mvc_book set bname=?,price=? where bid=?";
Connection con=null;
PreparedStatement ps=null;
try {
con=DBHelper.getConnection();
ps=con.prepareStatement(sql);
ps.setString(1, book.getBname());
ps.setFloat(2, book.getPrice());
ps.setInt(3, book.getBid());
ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.close(con, ps, null);
}
}
public void delBook(Book book) {
String sql="delete from t_mvc_book where bid=?";
Connection con=null;
PreparedStatement ps=null;
try {
con=DBHelper.getConnection();
ps=con.prepareStatement(sql);
ps.setInt(1, book.getBid());
ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}finally {
DBHelper.close(con, ps, null);
}
}
/**
* 查所有
* @param book
*/
public List<Book> queryBookPager(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SQLException {
String sql="select * from t_mvc_book where 1=1 ";
if(StringUtils.isBlank(book.getBname())) {
sql+=" and bname like '%"+book.getBname()+"%'";
}
sql+=" order by bid desc";
return super.executeQuery(sql, pageBean,new CallBack<Book>() {
@Override
public List<Book> forEach(ResultSet rs) {
return CommonUtils.toList(rs,Book.class);
}
});
}
@Override
public Book querySingleBook(Book book) {
String sql="select * from t_mvc_book where bid=?";
List<Book> list = super.executeQuery(sql, null, new CallBack<Book>() {
@Override
public List<Book> forEach(ResultSet rs) throws SQLException, Exception {
return CommonUtils.toList(rs, Book.class);
}
});
if(null!=list||0!=list.size()) {
return list.get(0);
}
else {
return null;
}
}
}
config.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/bookAction" type="com.xy.web.BookAction">
<forward name="success" path="/bookAction?methodName=queryBookPager" redirect="true" />
<forward name="list" path="/bookList.jsp" redirect="false" />
<forward name="edit" path="bookEdit.jsp"></forward>
<forward name="detail" path="bookDetail.jsp"></forward>
</action>
</config>
bookList.jsp(主页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="showMessage.jsp" %>
<!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}/bookAction.action?MethodName=list" method="post">
书本名称:<input type="text" name="bname" />
<input type="submit" value="查询" /><a href="bookAdd.jsp">新增书本信息</a>
<input type="hidden" name="methodName" value="queryBookPager" />
</form>
<table border="1px">
<th>书本编号</th>
<th>书本名称</th>
<th>书本价格</th>
<tbody>
<c:forEach items="${books}" var="book">
<tr>
<td>${book.bid}</td>
<td>${book.bname}</td>
<td>${book.price}</td>
<td>
<a href="bookAction.action?methodName=delBook&&bid=${book.bid }">删除</a>
<a href="bookAction.action?methodName=querySingleBook&type=edit&bid=${book.bid }">修改</a>
<a href="bookAction.action?methodName=querySingleBook&type=detail&bid=${book.bid }">详情</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
bookAdd.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>Insert title here</title>
</head>
<body>
<h1>新增书本</h1>
<form action="bookAction.action" method="post">
<input type="hidden" name="bid" />
书本名称:<input type="text" name="bname" /><br/>
书本价格:<input type="text" name="price" /><br/>
<input type="submit" value="增加" />
<input type="hidden" name="methodName" value="addBook" //>
</form>
</body>
</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>Insert title here</title>
</head>
<body>
<h1>修改书本信息</h1>
<form action="bookAction.action" method="post">
<input type="hidden" name="bid" value="${book.bid }" />
书本名称:<input type="text" name="bname" value="${book.bname }" /><br/>
书本价格:<input type="text" name="price" value="${book.price }" /><br/>
<input type="submit" value="修改" />
<input type="hidden" name="methodName" value="editBook" //>
</form>
</body>
</html>
showMessage.jsp(封装的消息提示页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<scrip>
var msg='${message}';
if(msg){
window.onload=function(){
alert(msg);
};
}
</scrip>
<c:remove var="message" scope="session"/>