当前位置:网站首页>自定义MVC的使用
自定义MVC的使用
2022-06-30 02:58:00 【安离九歌】
目录
前言
一、搭建自定义mvc框架环境
首先我们将自定义的mvc打成jar包
--------------------------------------------------------------------------------------------------------------------------------

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

可以在我的桌面看到jar包了

创建一个新项目,导入依赖

在新建的项目中,将分页标签以及相关的助手类导入
添加配置文件、web.xml配置
二、基础增删改
代码如下:
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>{
//查询
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();
//前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值为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;
});
}
// 增加
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 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 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();
}
}
测试代码如下:
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");
}
}
查询全部

增加
先查询看一下数据库中是否存在该书籍
@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 testEdit() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
数据库查询,是否修改成功
删除
@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();
}
}
进数据库看是否删除成功
三、通用增删改
对比增删改会发现除了SQL语句以及占位符赋值外其他都相同,那么我们可以写一个通用方法,又因为需要赋值的不一样,我们定义一个数组将需要赋值的字段放入数组中。
public int excuteUpdate(String sql ,T t ,String[] attrs) throws Exception {
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
// 将T的某一个属性的值加到pst 中
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>{
//查询
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();
//前台jsp传递到后台,只要传了就有值,没传就是默认值,默认值为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;
});
}
// 增加
// 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"});
}
// 删除
// 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"});
}
// 修改
// 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
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 testEdit() {
Book book = new Book(111234321, "12343212222" , 1234321);
try {
bd.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
数据库查询,是否修改成功
删除
@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();
}
}
进数据库看是否删除成功
四、查询删除
<%@ 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>书籍列表</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="请输入书籍名称">
</div>
<button type="submit" class="btn btn-primary mb-2">查询</button>
</form>
<table class="table table-striped bg-success">
<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>
</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;
}
//增
public String add(HttpServletRequest req,HttpServletResponse resp) {
try {
bd.add(book);
} catch (Exception e) {
e.printStackTrace();
}
//代表跳到查询界面
return "toList";
}
//删
public String del(HttpServletRequest req,HttpServletResponse resp) {
try {
bd.del(book);
} catch (Exception e) {
e.printStackTrace();
}
//代表跳到查询界面
return "toList";
}
// 改
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("list", list);
req.setAttribute("pageBean", pagebean);
} catch (Exception e) {
e.printStackTrace();
}
//代表执行查询展示
return "list";
}
// 跳转新增修改
public String preEdit(HttpServletRequest req,HttpServletResponse resp) {
try {
int bid = book.getBid();
if(bid != 0) {
//传递bid到后台,有且只能查一条数据,list集合中只有一条
List<Book> list = bd.list(book, null);
req.setAttribute("b", list.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
//代表跳到查询界面
return "toEdit";
}
}
五、新增修改的前端实现
<%@ 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 page Jump and parameter transfer
- CMake教程系列-01-最小配置示例
- Interrupt operation: abortcontroller learning notes
- 在php中字符串的概念是什么
- 【直播笔记0629】 并发编程二:锁
- Visual HTA form designer htamaker interface introduction and usage, Download | HTA VBS visual script writing
- Network neuroscience -- a review of network Neuroscience
- 【微信小程序】条件渲染 列表渲染 原来这样用?
- How does native JS generate Jiugong lattice
- Global and Chinese market of subscription revenue management software 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢

Uniapp address translation latitude and longitude

Summary of knowledge points about eigenvalues and eigenvectors of matrices in Chapter 5 of Linear Algebra (Jeff's self perception)

Prompt learning a blood case caused by a space

How to prevent duplicate submission under concurrent requests

福利抽奖 | 开源企业级监控Zabbix6.0都有哪些亮点

Study diary: February 15, 2022

【实战技能】如何撰写敏捷开发文档

【直播笔记0629】 并发编程二:锁

Intel-Hex , Motorola S-Record 格式详细解析

Federal learning: dividing non IID samples by Dirichlet distribution
随机推荐
迅為恩智浦iTOP-IMX6開發平臺
快速排序、聚簇索引、寻找数据中第k大的值
What about punctuation in the first column of unity text
2. successfully solved bug:exception when publishing [Failed to connect and initialize SSH connection...
怎么利用Redis实现点赞功能
Global and Chinese markets for wireless security in LTE networks 2022-2028: Research Report on technology, participants, trends, market size and share
002 color classification
SQLite使用
Some technology sharing
身份证号的严谨判断精确到队后一位
C console format code
在php中字符串的概念是什么
【实战技能】如何撰写敏捷开发文档
CMake教程系列-04-编译相关函数
Prompt learning a blood case caused by a space
CMake教程系列-03-依赖管理
Cross domain, CORS, jsonp
多卡服务器使用
Interrupt operation: abortcontroller learning notes
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







