1. Review of the previous section
In the previous section, we learned about:
1. Turn the Action container in the central controller into controllable!
2. Invoking business code for reflection, the final page jumps
3. There are too many code optimization fields in the background of jsp page parameter transfer!
2. Preparatory work for project deployment
1. Project operating environment configuration
1.1. First create a new web project and complete the xml construction
Then name it, click the next point to the end until this appears
Check it, next!
1.2 Load jar
Put our jar in the security directory of the web project
Then add our jar to the project during add buth
1.3 The preparation work is over
Create a new utils package, add our data connection driver, filter, connection protection file, paging code, and general method basedao into the utils package
3. Officially launch the project
1. Create entity package
Define the required attributes and provide get and set methods; tostring, with parameters and without parameters
2. Establish a general query method
2.1. Inherit BaseDao<Book> to realize general query
public List<Book> list(Book book, PageBean pageBean) throws Exception {
String sql = "select *from t_mvc_book where 1=1 ";
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);
}
3. Addition, deletion and modification of the old version, and addition, deletion and modification
3.1 Additions, deletions and modifications of the old version
// 增加
public int add(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBid());
ps.setObject(2, book.getBname());
ps.setObject(3, book.getPrice());
return ps.executeUpdate();
}
//删除
public int del(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid=? ";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBid());
return ps.executeUpdate();
}
public int edit(Book book) throws Exception {
String sql = " update t_mvc_book set bname=?,price=? where bid=?";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBname());
ps.setObject(2, book.getPrice());
ps.setObject(3, book.getBid());
return ps.executeUpdate();
}
shortcoming:
Duplicate code:
Connection conn = DBAccess.getConnection();
PreparedStatement ps =conn.prepareStatement(sql);
Repeat process:
ps.setObject(1, book.getBid());
ps.setObject(2, book.getBname());ps.setObject(3, book.getPrice());
3.2 Additions, deletions and changes in the new version
3.2.1 Encapsulate repetitive code in basedao
Use an object collection to store the attributes of the entity, and then use a for loop to subscript its purpose: to traverse the required attributes according to the operation, then operate through reflection, and finally add the set value
* 通用的增删改方法
* @param book
* @throws Exception
* sql:sql语句
* T:实体
* attrs:实体属性
*/
public int executeUpdate(String sql, T t, String[] attrs) throws Exception {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
for (int i = 0; i < attrs.length; i++) {
Field f = t.getClass().getDeclaredField(attrs[i]);
f.setAccessible(true);
pst.setObject(i+1, f.get(t));
}
return pst.executeUpdate();
}
3.2.2 new version
You only need to call that method, write the sql statement according to the requirements, and then return the sql statement, the entity, and the elements in the set through return
/**
* 通用增删改
*/
//增加
public int add(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
}
//删除
public int del(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid=? ";
return super.executeUpdate(sql, book, new String[] {"bid"});
}
//修改
public int edit(Book book) throws Exception {
String sql = "update t_mvc_book set bname=?,price=? where bid=? ";
return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
}
4. juin test
Select the category, crtl+n to create a class Juint test case for the code to test
4.1 Method testing
Implementation ideas:
1. First in the outermost layer: call the privatized dao method
2. Instantiate the entity inside the method
3. Then pass the dao. method name
4. Of course, specific analysis of the specific situation
package com.lz.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import com.lz.entity.Book;
import com.lz.utils.PageBean;
public class BookDaoTest {
private BookDao bk=new BookDao();
@Test
public void testList() throws Exception {
Book book=new Book();
book.setBname("圣墟");
PageBean pageBean=new PageBean();
//pageBean.setPage(3);
pageBean.setPagination(false);
List<Book> list = bk.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testAdd() throws Exception {
Book book=new Book(16,"圣墟嘿嘿嘿",12f);
bk.add(book);
}
@Test
public void testDel() throws Exception {
Book book=new Book();
book.setBid(16);
bk.del(book);
}
@Test
public void testEdit() throws Exception {
Book book=new Book(16,"圣墟嘿嘿嘿",12f);
bk.edit(book);
}
}
4.2 Method call
Method of choosing
When green appears, it means there is no problem with the method
5. Configure the xml file and implement some methods through reflection
5.1. Configure mvc.xml
The name attribute is: the return value of our return method in Bookaction
path is: jump path
5.2 Configure tid file
The tag-class attribute is: the pagination code path we configured
6. Implement the web interface
6.1 Data display interface
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="z" uri="http://jsp.veryedu.cn" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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">
<link
href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
rel="stylesheet">
<script
src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="bname"
placeholder="请输入书籍名称">
<a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid }">增加</a>
</div>
<button type="submit" class="btn btn-primary mb-2">查询</button>
</form>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">书籍ID</th>
<th scope="col">书籍名</th>
<th scope="col">价格</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid }">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=tdel&bid=${b.bid }">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
6.1.2 Effect drawing
6.2 Addition, modification
6.2.1 Code
Due to the addition and modification, we share a jsp interface. When we pass parameters, we need to make a judgment on the parameters and use the ternary operator. If b is the addition operation, otherwise it is the modification operation.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="z" uri="http://jsp.veryedu.cn"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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 class="form-inline"
action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
书籍ID:<input type="text" name="bid" value="${b.bid }"><br>
书籍名称:<input type="text" name="bname" value="${b.bname }"><br>
书籍价格:<input type="text" name="price" value="${b.price }"><br>
<input type="submit">
</form>
</body>
</html>
6.2.2 Effect drawing