当前位置:网站首页>General addition, deletion, modification and query of custom MVC
General addition, deletion, modification and query of custom MVC
2022-07-28 23:35:00 【I love coriander TVT】
One 、 Build custom MVC Framework environment
Customize what we wrote before MVC Frame guide assembly jar package , Create a new addition, deletion, modification and query item and import this jar package , Then configure xml file

Especially the arrow position in the screenshot needs attention , Otherwise, it will lead to our jar The package is not working properly
Two 、 General addition, deletion, modification and query
1. generic class BaseDao
First, we define a general addition, deletion, modification and query Because all additions, deletions, and modifications need to commit transactions , Query does not need , So we rewrite the addition and deletion into a general method , When calling methods in subclasses, you only need to define different sql sentence , And parameters are ok 了
package com.zjy.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;
public class BaseDao<T> {
public List<T> executeQuery( String sql,PageBean pagebean,CallBack<T> callBack) throws Exception{
/**
* 1. Get the database connection
* 2. Get preparstatement
* 3. perform sql sentence
*/
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
if(pagebean!=null&&pagebean.isPagination()) {
String countsql = getCountsql(sql);
con = DBAccess.getConnection();
ps = con.prepareStatement(countsql);
rs = ps.executeQuery();
if(rs.next()) {
pagebean.setTotal(rs.getString("n"));
}
String pageSql= getpageSql(sql,pagebean);
con = DBAccess.getConnection();
ps = con.prepareStatement(pageSql);
rs = ps.executeQuery();
}else {
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
// Querying different tables must deal with different result sets
return callBack.foreach(rs);
}
/**
* Splice section N Of page data sql
* @param sql
* @param pagebean
* @return
*/
private String getpageSql(String sql, PageBean pagebean) {
return sql +" limit "+pagebean.getStartIndex()+" , "+pagebean.getRows();
}
/**
* The total number of records that meet the conditions is Sql
* @param sql
* @return
*/
private String getCountsql(String sql) {
// TODO Auto-generated method stub
return " select count(1) as n from ("+sql+") t";
}
/**
* General addition, deletion and modification
* @param sql sql sentence
* @param t Generic class
* @param strings Attribute array
* @return
* @throws Exception Throw exceptions
*/
public int executeUpdate(String sql,T t,String[] strings) throws Exception {
Connection con = DBAccess.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
// take t A corresponding value of is added to ps In the object
for (int i = 0; i < strings.length; i++) {
Field f = t.getClass().getDeclaredField(strings[i] );
f.setAccessible(true);
f.get(t);
ps.setObject(i+1, f.get(t));// Subscript from 0 Start
}
return ps.executeUpdate();
}
}
2.BookDao
Depending on the method ,sql Statements and parameters are also different
package com.zjy.dao;
import java.util.ArrayList;
import java.util.List;
import com.zjy.entity.Book;
import com.zjy.util.BaseDao;
import com.zjy.util.PageBean;
import com.zjy.util.StringUtils;
public class BookDao extends BaseDao<Book>{
/**
* Inquire about
* @param book Entity class
* @param pagebean Pagination
* @return
* @throws Exception Throw exceptions
*/
public List<Book> list(Book book,PageBean pagebean) throws Exception{
String sql = "select * from t_mvc_book where 1 = 1";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +=" and bname like'%"+bname+"%'";
}
int bid = book.getBid();
if(bid !=0) {
sql +=" and bid = "+bid;
}
// Call the query method of the parent class
return super.executeQuery(sql, pagebean, rs->{
List<Book> list = new ArrayList<>();
try {
while(rs.next()) {
list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
});
}
/**
* Increase method
* @param book Physical books
* @return General addition, deletion and modification methods in the parent class
* @throws Exception
*/
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"});
}
/**
* Delete method
* @param book Physical books
* @return General addition, deletion and modification methods in the parent class
* @throws Exception
*/
public int delete(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid = ?";
return super.executeUpdate(sql, book, new String[] {"bid"});
}
/**
* Modification method
* @param book Physical books
* @return General addition, deletion and modification methods in the parent class
* @throws Exception
*/
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"});
}
}
3、 stay BookAction Write the corresponding method in
Follow the rule of inheritance before implementation , Call the methods of the parent class and interface respectively
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private Book book = new Book();
private BookDao bd = new BookDao();
@Override
public Book getModel() {
// TODO Auto-generated method stub
return null;
}
// increase
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
bd.add(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
// Delete
public String delete(HttpServletRequest req, HttpServletResponse resp) {
try {
bd.delete(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
// modify
// increase
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
bd.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String list(HttpServletRequest req,HttpServletResponse resp) {
try {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Book> list=bd.list(book, pageBean);
req.setAttribute("books", list);
req.setAttribute("pageBean", pageBean);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
public String toEdit(HttpServletRequest req,HttpServletResponse resp) {
try {
if(book.getBid()!=0) {
List<Book> list=bd.list(book, null);
req.setAttribute("b", list.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
return "toEdit";
}4、 stay Junit Medium test
package com.zjy.dao;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.zjy.entity.Book;
class BookDaoTest {
private BookDao bookDao=new BookDao();
@Test
public void testList() {
try {
List<Book> list = bookDao.list(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// increase
@Test
public void testAdd() {
Book book = new Book(123, " Xiao Zhu ", 9999);
try {
bookDao.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// modify
@Test
public void testEdit() {
Book book = new Book(123, " Father Zhu ", 9999);
try {
bookDao.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Delete
@Test
public void testDelete() {
Book book = new Book(123, " Father Zhu ", 9999);
try {
bookDao.delete(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3、 ... and 、 front end Jsp Interface
1、 main interface
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.zhujiayin.zjy" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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> List of books </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=" Please enter the name of the book ">
<!-- <input name="rows" value="20" type="hidden"> -->
<!-- I don't want to -->
<input name="pagination" value="false" type="hidden">
</div>
<button type="submit" class="btn btn-primary mb-2"> Inquire about </button>
<a class="btn btn-primary mb-2"
href="${pageContext.request.contextPath }/book.action?methodName=toEdit"> newly added </a>
</form>
<table class="table table-striped bg-success">
<thead>
<tr>
<th scope="col"> Books ID</th>
<th scope="col"> Book title </th>
<th scope="col"> Price </th>
<th scope="col"> operation </th>
</tr>
</thead>
<tbody>
<c:forEach var="b" items="${books }">
<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}"> modify </a>
<a
href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}"> Delete </a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- This line of code is equivalent to dozens of lines in front of the paging requirements -->
<z:page pageBean="${ pageBean}"></z:page>
</body>
</html>2、BookEdit( Add and modify interface )
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.zhujiayin.zjy" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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> New books / modify </title>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
Books ID:<input type="text" name="bid" value="${b.bid }"><br>
Book name :<input type="text" name="bname" value="${b.bname }"><br>
Book price :<input type="text" name="price" value="${b.price }"><br>
<input type="submit">
</form>
</body>
</html>Four 、 summary
1、 Use customization MVC Steps for :
1.1、 Import self exported customization MVC.jar package
1.2、 Make the corresponding configuration of the framework ( Before the import MVC.jar Packet dependent jar package )
1.3 、 Everything remains the same. (jsp Interface ,bookaction、dao layer 、entity)
2、 The difference between general addition, deletion, modification and query is the same :
2.1 Common ground : Add, delete, change and query, and finally jump back to the query interface
2.2 Difference :2.2.1: Inquire about :bookList.jsp Return value :list
2.2.2: Add, delete and modify to confirm :book.action?methodName=list Return value :toList
2.2.3 Add the interface corresponding to the modification jump :bookEdit.jsp The return value is toEdit
边栏推荐
- In order for digital retail to continue to play its role, we need to give new connotation and significance to digital retail
- 集火全屋智能“后装市场”,真正玩得转的没几个
- Kotlin JVM annotation
- Rhce第二天
- How does VR panorama entrepreneurship expand the market? How to make the road of entrepreneurship smoother?
- Advanced C language: pointer (2)
- 使用这个,你发的消息就无法被监控了
- 当初的“你“为什么做测试/开发程序员?自己存在的价值......
- Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]
- 事件抽取文献整理(2018)
猜你喜欢

Development of small programs ②

Applet Download Preview PDF, document cannot open solution

Basic concept of MySQL database and deployment of MySQL version 8.0 (I)

Arduino框架下STM32F103C系列单片机引脚映射关系
![Trivy [2] tool vulnerability scanning](/img/7a/c1012c75b23076f5a9b09e5756adba.png)
Trivy [2] tool vulnerability scanning

trivy【3】自定义扫描策略

Price for volume has encountered "six consecutive declines" in sales. Can Volvo, which is no longer safe, turn around?

Assembly analysis swift polymorphism principle

22 Niuke multi school Day1 I - Introduction to chiitoitsu DP

英特尔数据中心GPU正式发货,以开放灵活提供强劲算力
随机推荐
这款全网热评的无线路由器,到底有什么特别?
Sdwebimage source code combs 5 author motivation, modifies directory, and changes inheritance relationship
二叉搜索树
华为无线设备配置利用WDS技术部署WLAN业务
Swift type attribute and its attentions
How to embed AI digital human function in VR panorama? Create a cloud experience
Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]
LabVIEW对VISA Write和Read函数的异步和同步
General principles of software quality
[MySQL series] addition, deletion, modification and query of MySQL tables (Advanced)
Sdwebimage source code comb 4 # introduce several usages of existing code
金仓数据库 KingbaseES与Oracle的兼容性说明(2. 数据类型)
All aspect visual monitoring of istio microservice governance grid (microservice architecture display, resource monitoring, traffic monitoring, link monitoring)
被忽视的智能电视小程序领域
The development mode of digital retail dominated by traffic is only the beginning
集火全屋智能“后装市场”,真正玩得转的没几个
Development of small programs ②
trivy【3】自定义扫描策略
Terminal output G_ Debug() information
mongodb索引添加、查看、导出、删除