首先导入需要用到的jar包和通用分页的.tld文件:
然后进行增删改查:
先对t_mvc_book文件进行操错,所以先写一个书籍的实体类Book:
如下:
package com.lx.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里面写增,删,改方法:
package com.lx.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.lx.entity.Book;
/**
* 用来处理所有表的通用的增删改查的基类
*
* 查询指的是:通用的分页查询
* @author Administrator
*
* @param <T>
*/
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 SQLException, InstantiationException, IllegalAccessException{
List<T> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
if(pageBean != null && pageBean.isPagination()) {
// 分页代码
/*
* 1、分页是与pagebean中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());
}
// select * from t_mvc_book where bname like '%圣墟%' limit 20,10
String pageSql = getPageSql(sql,pageBean);
pst = con.prepareStatement(pageSql);
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 attrs 代表了sql语句中的问号 "bname","price","bid"
* @param t 实体类(里面包含了参数值)
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int executeUpdate(String sql,String[] attrs,T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
Field field = null;
for (int i = 0; i < attrs.length; i++) {
try {
field = t.getClass().getDeclaredField(attrs[i]);
field.setAccessible(true);
pst.setObject(i+1, field.get(t));
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
}
int num = pst.executeUpdate();
DBAccess.close(con, pst, null);
return num;
}
}
在建一个BookDao,然后继承BaseDao:
package com.lx.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.lx.entity.Book;
import com.lx.util.BaseDao;
import com.lx.util.PageBean;
import com.lx.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
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 IllegalArgumentException
* @throws IllegalAccessException
*/
public int add(Book book) throws SQLException, 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 IllegalArgumentException
* @throws IllegalAccessException
*/
public int edit(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, new String[] {"bname","price","bid"}, book);
}
/** 删除方法:
* @param book
* @return
* @throws SQLException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int del(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql = "delete from t_mvc_book where bid = ?";
return super.executeUpdate(sql, new String[] {"bid"}, book);
}
public static void main(String[] args) {
BookDao bookDao = new BookDao();
Book book = new Book(141313, "xxx", 56f);
try {
bookDao.del(book);
} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
}
在子控制器接收获取到的值并且实行增,删,改,查方法:
package com.lx.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lx.dao.BookDao;
import com.lx.entity.Book;
import com.lx.framework.ActionSupport;
import com.lx.framework.ModelDriven;
import com.lx.util.PageBean;
public class BookAction extends ActionSupport implements ModelDriven<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 (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
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 (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
return "edit";
}
/** 增加方法:
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
this.bookDao.add(book);
} catch (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 (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 (IllegalArgumentException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel() {
return book;
}
}
在一个写xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- <action path="/cal_add" type="com.lx.web.AddCalAction"> -->
<!-- <forward name="rs" path="/rs.jsp" redirect="false" /> -->
<!-- </action> -->
<action path="/book" type="com.lx.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>
配置一下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>lx_mvc</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.lx.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.lx.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>mvcXmlLocation</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>
然后就是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="/LHJ" 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>书籍主页</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>
<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>书籍的编辑页面</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="ok">
</form>
</body>
</html>