1、第一步准备工作
1.1 将自己写好的东西打成jar包,然后加入项目中
1.2 建包,在这里需要五个包,entity,util,dao,tag,web
1.3 导入自己所需要的jar包,和工具类,还有配置文件
下面截图就是我们做好的增删查改准备工作
注意:. 增/删/改用重定向,查询用转发
2、第二步写实体类
代码如下:
package com.zrh.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();
}
}
3、第三步写dao方法
3.1 bookdao继承 BaseDao传一个Book
/**
* 查询
* @author zrh
*
*/
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";
if(StringUtils.isNotBlank(book.getBname())) {//如果name不是空的就拼进SQL语句中
sql += " and bname like '%+book.getBname()+%' ";
}
return super.executeQuery(sql, Book.class, pageBean);
}
/**
* 增加
* @param book
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws NoSuchFieldException
*/
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 delete(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 update(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.2 BaseDao.java 把通用的增删改增强
/**
* 通用的增删改方法
* @param sql 增删改的sql语句
* @param attrs ?所代表的是实体类的属性
* @param t 实体类的实例
* @return
* @throws SQLException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public int executeUpdate(String sql, String[] attrs,T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Connection con = (Connection) DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
for (int i = 0; i < attrs.length; i++) {
Field field = t.getClass().getDeclaredField(attrs[i]);//获取里面的属性对象
field.setAccessible(true);
pst.setObject(i+1, field.get(t));;
}
return pst.executeUpdate();
}
3.3 写一个测试类BookDaoTest.java
package com.zrh.dao;
import java.sql.SQLException;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.zrh.entity.Book;
class BookDaoTest {
private BookDao bookDao = new BookDao();
private Book book = null;
@BeforeEach
void setUp() throws Exception {
book = new Book();
}
@AfterEach
void tearDown() throws Exception {
}
@Test
void testList() {
try {
List<Book> list = this.bookDao.list(book, null);
System.out.println(list.size());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
void testAdd() {
book.setBid(151);
book.setBname("斗破");
book.setPrice(10);
try {
this.bookDao.add(book);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
void testDelete() {
book.setBid(151);
try {
this.bookDao.delete(book);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
void testUpdate() {
book.setBid(151);
book.setBname("遮天");
book.setPrice(102);
try {
this.bookDao.update(book);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上测试完之后就到了第四步
4、第四步 子控制器
package com.zrh.web;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriven;
import com.zrh.dao.BookDao;
import com.zrh.entity.Book;
import com.zrh.util.PageBean;
/**
* 子控制器
* @author zrh
*
*/
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private BookDao bookDao = new BookDao();
private Book book = new Book();
/**
* 查询分页展示的数据
* @param req
* @param resp
* @return
*/
public String list(HttpServletRequest req,HttpServletResponse resp) {
try {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Book> list = this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pageBean", pageBean);
System.out.println(list.size());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
/**
* 增加书籍
* @param req
* @param resp
* @return
*/
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
int rsCode = this.bookDao.add(book);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 删除书籍
* @param req
* @param resp
* @return
*/
public String delete(HttpServletRequest req,HttpServletResponse resp) {
try {
int rsCode = this.bookDao.delete(book);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
/**
* 加载需要修改的数据
* @param req
* @param resp
* @return
*/
public String load(HttpServletRequest req,HttpServletResponse resp) {
try {
List<Book> list = this.bookDao.list(book, null);
req.setAttribute("book", list.get(0));
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toEdit";
}
/**
* 开始修改
* @param req
* @param resp
* @return
*/
public String update(HttpServletRequest req,HttpServletResponse resp) {
try {
int rsCode = this.bookDao.update(book);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel(HttpServletRequest arg0) throws IllegalAccessException, InvocationTargetException {
// TODO Auto-generated method stub
return book;
}
}
5、第五步 配置 mvc.xml和web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/bookAction" type="com.zrh.web.BookAction">
<forward name="list" path="/bookList.jsp" redirect="false" />
<forward name="toList" path="bookAction.action?methodName=list" redirect="true" />
<forward name="toEdit" path="/bookEdit.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>T224_mvc_crud</display-name>
<!-- 配置中文乱码过滤器 -->
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.zrh.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Servlet核心控制器 -->
<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>com.zking.framework.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
以上五步都是后台的页面,下面我们进入前台的功能实现
6、第六步 增删改的功能页面展示
页面我们有主页面,和新增修改页面,我们把新增修改页面放在一起
首先是主页面:
<%@ 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="/zrh" 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>
<script type="text/javascript">
function add(){
window.location.href = "bookEdit.jsp";
}
function update(bid){
window.location.href = "${pageContext.request.contextPath}/bookAction.action?methodName=load&&bid="+bid;
}
function del(bid){
window.location.href = "${pageContext.request.contextPath}/bookAction.action?methodName=delete&&bid="+bid;
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/bookAction.action?methodName=list"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<button onclick="add();">新增</button>
<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>
<button onclick="update(${b.bid });">修改</button>
<button onclick="del(${b.bid });return confirm('确定要删除吗')">删除</button>
</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>Insert title here</title>
<script type="text/javascript">
function doSubmit(bid){
var bookForm = document.getElementById("bookForm");
if(bid){
//修改时执行
bookForm.action = '${pageContext.request.contextPath}/bookAction.action?methodName=update';
}else{
//新增时执行
bookForm.action = '${pageContext.request.contextPath}/bookAction.action?methodName=add';
}
bookForm.submit();
}
</script>
</head>
<body>
<form id="bookForm" action="" method="post">
bid:<input type="text" name="bid" value="${book.bid }"><br>
bname:<input type="text" name="bname" value="${book.bname }"><br>
price:<input type="text" name="price" value="${book.price }"><br>
<input type="submit" value="提交" onclick="doSubmit('${book.bid}');">
</form>
</body>
</html>
页面展示结果为:
主页面:
增加页面:
修改页面:
到这里就结束了!