自定义mvc的最后一次升级
1、把所写好的工具类导成jar包
找到JAR file选择你要导出的文件路径:
最后点击finish,就把文件成功的导出来了
2、dao层 通用的增删改方法
BaseDao
package com.leiyuanlin.dao;
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.leiyuanlin.util.DBAccess;
import com.leiyuanlin.util.PageBean;
/**
* T代表你要对哪个实体类对应表进行分页查询
* @author 2018101801
*
* @param <T>
*/
public class BaseDao<T> {
/**
*
* @param sql 查询不同的实体类,那么对应的sql不同,所以需要传递
* @param clz 生产出不同的实体类对应的实例,然后装进list容器中返回
* @param pageBean 决定是否分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
Connection con = DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
if(pageBean != null && pageBean.isPagination()) {
// 3、考虑该方法可以进行分页
// 需要分页
// 3.1 算符合总记录数
String countSql = getCountSql(sql);
pst = con.prepareStatement(countSql);
rs = pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getLong(1)+"");
}
// 3.2 查询出符合条件的结果集
String pageSql = getPageSql(sql,pageBean);
pst = con.prepareStatement(pageSql);
rs = pst.executeQuery();
}else {
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
}
List<T> list = new ArrayList<>();
T t;
while(rs.next()) {
/*
* 1、实例化一个book对象(该对象是空的,里面的属性没有值)
* 2、取book的所有属性,然后给其赋值
* 2.1 获取所有属性对象
* 2.2 给属性对象赋值
* 3、赋完值的book对象装进list容器中
*/
// list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
t = (T) clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
field.set(t, rs.getObject(field.getName()));
}
list.add(t);
}
DBAccess.close(con, pst, rs);
return list;
}
/**
* 利用原生sql拼接出符合条件的结果集的查询sql
* @param sql
* @param pageBean
* @return
*/
private String getPageSql(String sql, PageBean pageBean) {
return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* 获取符合条件的总记录数的sql语句
* @param sql
* @return
*/
private String getCountSql(String sql) {
return "select count(1) from ("+sql+") t";
}
/**
*
* @param sql 决定增删改的一种
* @param attrs 决定?的位置 new String[]{"bid","bname",...}
* @param t 要操作的实体类
* @return
* @throws SQLException
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int executeUpdate(String sql, String[] attrs ,T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
for (int i = 1; i <= attrs.length; i++) {
Field field = t.getClass().getDeclaredField(attrs[i-1]);
field.setAccessible(true);
pst.setObject(i, field.get(t));
}
int num = pst.executeUpdate();
DBAccess.close(con, pst, null);
return num;
}
}
bookDao(继承于BaseDao)
package com.leiyuanlin.dao;
/**
* 目的:做一个通用的分页的查询方法
* 1、利用s2的知识完成一个普通的查询方法
* 2、将原有的查询方法进行反射优化,转变成一个可以被所有实体类dao层所继承的通用查询方法
* 3、考虑该方法可以进行分页
* 3.1 算总记录数
* 3.2 查询出当前页的结果集
*
* @author 2018101801
*
*/
import java.sql.SQLException;
import java.util.List;
import com.leiyuanlin.entity.Book;
import com.leiyuanlin.util.PageBean;
import com.leiyuanlin.util.StringUtils;
public class BookDao extends BaseDao<Book>{
/**
* 查询方法
* @param book 封装着jsp传递过来的查询参数
* @param pageBean 决定dao层的list调用时是否分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<Book> list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
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);
}
/**
* 新增
* @param book
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int add(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, new String[] {"bid","bname","price"}, book);
}
/**
* 删除
* @param book
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int del(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String sql = "delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, new String[] {"bid"}, book);
}
/**
* 修改
* @param book
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int edit(Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, new String[] {"bname","price","bid"}, book);
}
}
3、web层(BookAction)
package com.leiyuanlin.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.leiyuanlin.dao.BookDao;
import com.leiyuanlin.entity.Book;
import com.leiyuanlin.framework.ActionSupport;
import com.leiyuanlin.framework.ModelDrivern;
import com.leiyuanlin.util.PageBean;
public class BookAction extends ActionSupport implements ModelDrivern<Book>{
private Book book = new Book();
private BookDao bookDao = new BookDao();
/**
* 分页查询
* @param req
* @param resp
* @return
*/
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 (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "list";
}
/**
* 跳转到增加或者修改页面
* @param req
* @param resp
* @return
*/
public String preSave(HttpServletRequest req,HttpServletResponse resp) {
// bid的类型是int类型,而int类型的默认值是0,如果jsp未传递bid的参数值,那么bid=0
if(book.getBid() == 0) {
System.out.println("增加逻辑...");
}else {
try {
// 修改数据回显逻辑
Book b = this.bookDao.list(book, null).get(0);
req.setAttribute("book", b);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
// 新增页面与修改页面是同一个jsp
return "edit";
}
/**
* 新增
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.add(book);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
/**
* 修改
* @param req
* @param resp
* @return
*/
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.edit(book);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
/**
* 删除
* @param req
* @param resp
* @return
*/
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
this.bookDao.del(book);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
| SQLException e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel() {
return book;
}
}
对mvc.xml进行配置
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/cal" type="com.leiyuanlin.web.CalAction">
<forward name="res" path="/res.jsp" redirect="false" />
</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.leiyuanlin.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.leiyuanlin.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
bookList.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="/leiyuanlin" 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">
<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="确定">
<input type="hidden" name="rows" value="15">
</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>
<z:page pageBean="${pageBean }"></z:page>
</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>
<form action="${pageContext.request.contextPath}/book.action" method="post">
<input type="hidden" name="methodName" value="${book.bname == null ? 'add' : 'edit' }">
书籍ID:<input type="text" name="bid" value="${book.bid }"><br>
书籍名称:<input type="text" name="bname" value="${book.bname }"><br>
书籍价格:<input type="text" name="price" value="${book.price }"><br>
<input type="submit">
</form>
</body>
</html>
注意:
在做增删改操作的时候用重定向,查询时用转发
这样做的目的是 阻止多次上传请求带来数据重复的影响
感谢观看!