当前位置:网站首页>Use of custom MVC
Use of custom MVC
2022-06-30 03:05:00 【An Li Jiu Ge】
Catalog
One 、 Build custom mvc Framework environment
Two 、 Basic addition, deletion and modification
3、 ... and 、 General addition, deletion and modification
5、 ... and 、 New and modified front-end implementation
Preface
One 、 Build custom mvc Framework environment
First of all, we will customize mvc become involved jar package
--------------------------------------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------------------------------------

You can see it on my desktop jar It's packed

Create a new project , Import dependence

In a new project , Import the paging label and related helper classes into
Add configuration file 、web.xml To configure
Two 、 Basic addition, deletion and modification
The code is as follows :
package com.zhw.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.zhw.entity.Book;
import com.zhw.util.BaseDao;
import com.zhw.util.DBAccess;
import com.zhw.util.PageBean;
import com.zhw.util.StringUtils;
public class BookDao extends BaseDao<Book>{
// Inquire about
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();
// The front desk jsp Pass it to the background , As long as it's passed, it's worth it , No transmission is the default value , The default value is 0
if(bid != 0) {
sql += " and bid = "+bid;
}
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 (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
});
}
// increase
public int add(Book book) throws Exception {
Connection con = DBAccess.getConnection();
String sql = "insert into t_mvc_book values(?,?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setObject(1, book.getBid());
pst.setObject(2, book.getBname());
pst.setObject(3, book.getPrice());
return pst.executeUpdate();
}
// Delete
public int del(Book book) throws Exception {
Connection con = DBAccess.getConnection();
String sql = "delete from t_mvc_book where bid = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setObject(1, book.getBid());
return pst.executeUpdate();
}
// modify
public int edit(Book book) throws Exception {
Connection con = DBAccess.getConnection();
String sql = "update t_mvc_book set bname=?,price=? where bid = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setObject(1, book.getBname());
pst.setObject(2, book.getPrice());
pst.setObject(3, book.getBid());
return pst.executeUpdate();
}
}
The test code is as follows :
package com.zhw.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zhw.entity.Book;
public class BookDaoTest {
private BookDao bd = new BookDao();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testList() {
try {
List<Book> list = bd.list(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testAdd() {
Book book = new Book(111234321, "1234321" , 1234321);
try {
bd.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testDel() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testEdit() {
fail("Not yet implemented");
}
}
Query all

increase
First, check whether the book exists in the database
@Test
public void testAdd() {
Book book = new Book(111234321, "1234321" , 1234321);
try {
bd.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Call the added method
Query the database again to see if the data exists
modify
@Test
public void testEdit() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Database query , Is the modification successful
Delete
@Test
public void testDel() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.del(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enter the database to see if the deletion is successful
3、 ... and 、 General addition, deletion and modification
Compared with the addition, deletion and modification, it will be found that except SQL Statement and placeholder assignment , So we can write a general method , And because different values need to be assigned , We define an array and put the fields to be assigned into the array .
public int excuteUpdate(String sql ,T t ,String[] attrs) throws Exception {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
// take T Add the value of one of the attributes of to pst in
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();
}
package com.zhw.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.zhw.entity.Book;
import com.zhw.util.BaseDao;
import com.zhw.util.DBAccess;
import com.zhw.util.PageBean;
import com.zhw.util.StringUtils;
public class BookDao extends BaseDao<Book>{
// Inquire about
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();
// The front desk jsp Pass it to the background , As long as it's passed, it's worth it , No transmission is the default value , The default value is 0
if(bid != 0) {
sql += " and bid = "+bid;
}
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 (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
});
}
// increase
// public int add(Book book) throws Exception {
// Connection con = DBAccess.getConnection();
// String sql = "insert into t_mvc_book values(?,?,?)";
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// pst.setObject(2, book.getBname());
// pst.setObject(3, book.getPrice());
// return pst.executeUpdate();
// }
public int add(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.excuteUpdate(sql , book, new String[] {"bid","bname","price"});
}
// Delete
// public int del(Book book) throws Exception {
// Connection con = DBAccess.getConnection();
// String sql = "delete from t_mvc_book where bid = ?";
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// return pst.executeUpdate();
// }
public int del(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid = ?";
return super.excuteUpdate(sql , book , new String[] {"bid"});
}
// modify
// public int edit(Book book) throws Exception {
// Connection con = DBAccess.getConnection();
// String sql = "update t_mvc_book set bname=?,price=? where bid = ?";
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBname());
// pst.setObject(2, book.getPrice());
// pst.setObject(3, book.getBid());
// return pst.executeUpdate();
// }
public int edit(Book book) throws Exception {
String sql = "update t_mvc_book set bname=?,price=? where bid = ?";
return super.excuteUpdate(sql , book , new String[] {"bname","price","bid"});
}
}
Test it :
Query all

increase
First, check whether the book exists in the database
@Test
public void testAdd() {
Book book = new Book(111234321, "1234321" , 1234321);
try {
bd.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Call the added method
Query the database again to see if the data exists
modify
@Test
public void testEdit() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Database query , Is the modification successful
Delete
@Test
public void testDel() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.del(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enter the database to see if the deletion is successful
Four 、 Query delete
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="z" uri="http://jsp.zhwLouis"%>
<%@ 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>Insert title here</title>
<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 ">
</div>
<button type="submit" class="btn btn-primary mb-2"> Inquire about </button>
</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>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
</tr>
</c:forEach>
</tbody>
</table>
<z:page PageBean="${pagebean }"></z:page>
</body>
</html>
package com.zhw.web;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhw.dao.BookDao;
import com.zhw.entity.Book;
import com.zhw.framework.ActionSupport;
import com.zhw.framework.ModelDriven;
import com.zhw.util.PageBean;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private Book book = new Book();
private BookDao bd = new BookDao();
@Override
public Book getModel() {
return book;
}
// increase
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
bd.add(book);
} catch (Exception e) {
e.printStackTrace();
}
// The representative jumps to the query interface
return "toList";
}
// Delete
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
bd.del(book);
} catch (Exception e) {
e.printStackTrace();
}
// The representative jumps to the query interface
return "toList";
}
// Change
public String edit(HttpServletRequest req,HttpServletResponse resp) {
try {
bd.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
// The representative jumps to the query interface
return "toList";
}
// check
public String list(HttpServletRequest req,HttpServletResponse resp) {
try {
PageBean pagebean = new PageBean();
pagebean.setRequest(req);
List<Book> list = bd.list(book,pagebean);
req.setAttribute("list", list);
req.setAttribute("pageBean", pagebean);
} catch (Exception e) {
e.printStackTrace();
}
// On behalf of the execution query presentation
return "list";
}
// Jump to add / modify
public String preEdit(HttpServletRequest req,HttpServletResponse resp) {
try {
int bid = book.getBid();
if(bid != 0) {
// Pass on bid Go backstage , There is and can only be one piece of data ,list There is only one in the set
List<Book> list = bd.list(book, null);
req.setAttribute("b", list.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
// The representative jumps to the query interface
return "toEdit";
}
}
5、 ... and 、 New and modified front-end implementation
<%@ 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?methodName=${empty b ? 'add' : 'edit'}" method="post" >
bid:<input type="text" name="bid" value="${b.bid }"><br>
bname:<input type="text" name="bname" value="${b.bname }"><br>
price:<input type="text" name="price" value="${b.price }"><br>
<input type="submit">
</form>
</body>
</html>边栏推荐
- 华为面试题: 分糖果
- Wechat applet +php to realize authorized login operation
- 怎样的外汇交易平台是有监管的,是安全的?
- &nbsp;与空格的区别
- 原生JS怎么生成九宫格
- How to set password complexity and timeout exit function in Oracle
- Tri rapide, index groupé, recherche de la plus grande valeur K dans les données
- 编译一个无导入表的DLL
- 如何在 JupyterLab 中把 ipykernel 切换到不同的 conda 虚拟环境?
- NLP text summary: data set introduction and preprocessing [New York Times annotated corpus]
猜你喜欢

Use of Arthas

golang bilibili直播彈幕姬

Prompt learning a blood case caused by a space

The broadcast module code runs normally in autojs4.1.1, but an error is reported in pro7.0 (not resolved)

广播模块代码在autojs4.1.1版本运行正常,但在pro7.0版本上运行报错(未解决)

Raki's notes on reading paper: neighborhood matching network for entity alignment

Golang BiliBili live broadcast bullet screen

How to switch ipykernel to a different CONDA virtual environment in jupyterlab?

Customize the buttons of jvxetable and the usage of $set under notes

Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery
随机推荐
快速排序、聚簇索引、尋找數據中第k大的值
Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery
CMake教程系列-02-使用cmake代碼生成二進制
How to switch ipykernel to a different CONDA virtual environment in jupyterlab?
Série de tutoriels cmake - 02 - génération de binaires à l'aide du Code cmake
How can redis+aop customize annotations to achieve flow restriction
Cmake tutorial series-03-dependency management
Auto.js学习笔记15:autojs的UI界面基础篇2
What is the concept of string in PHP
正则全匹配:密码由8位以上数字,大小写字母,特殊字符组成
重磅来袭--UE5的开源数字孪生解决方案
如何在 JupyterLab 中把 ipykernel 切换到不同的 conda 虚拟环境?
Cmake tutorial series -02- generating binaries using cmake code
mysqldump原理
行政路线编码 字母+数字的排序方式
Software testing skills, JMeter stress testing tutorial, transaction controller of logic controller (25)
Raki's notes on reading paper: Leveraging type descriptions for zero shot named entity recognition and classification
How to use redis to realize the like function
golang bilibili直播弹幕姬
2022 new test questions for safety management personnel of metal and nonmetal mines (small open pit quarries) and certificate examination for safety management personnel of metal and nonmetal mines (s







