目录
一、搭建自定义MVC框架环境
①将框架打成jar包导入新工程,并且把框架的依赖jar包导入进去
②将分页标签相关文件、及相关助手类导入
③框架的配置文件添加、以及web.xml的配置
解析:
①将框架打成jar包导入新工程,并且把框架的依赖jar包导入进去
②将分页标签相关文件、及星环助手类导入
二、基础的增删改
实体类:Book.Class
代码块展示:
package com.chenchen.entity;
/**
* 实体类:book
* @author ChenChen
*@date 2022年6月29日 上午9:19:59
*/
public class Book {
private int bid;
private String bname;
private float 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() {
// TODO Auto-generated constructor stub
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book( String bname, float price) {
this.bid = bid;
this.bname = bname;
this.price = price;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
数据库访问层:BookDao.Class
代码块展示:
package com.chenchen.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.chenchen.entity.Book;
import com.chenchen.util.BaseDao;
import com.chenchen.util.DBAccess;
import com.chenchen.util.PageBean;
import com.chenchen.util.StringUtils;
/**
* 数据库访问层
* @author ChenChen
*@date 2022年6月29日 上午10:26:03
*/
public class BookDao extends BaseDao<Book>{
// 查询
public List<Book> list(Book book,PageBean pageBean) throws Exception{
String sql = "select * from t_mvc_book 1=1 ";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +=" and banem 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<Book>();
// 处理结果集
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;
});//回调函数主要使用来处理我们的结果集
}
/**
* 增加
*@author ChenChen
* @since 2022.06.29
* @param book
* @return 影响行数
* @throws Exception
*/
public int add(Book book) throws Exception {
// 获得连接
Connection con = DBAccess.getConnection();
// sql语句
String sql="insert into t_mvc_book values(?,?,?)";
// 执行sql语句
PreparedStatement ps = con.prepareStatement(sql);
// 给站位符赋值
ps.setObject(1, book.getBid());
ps.setObject(2, book.getBname());
ps.setObject(3, book.getPrice());
// 返回影响行数
return ps.executeUpdate();
}
/**
* 删除
*@author ChenChen
* @since 2022.06.29
* @param book
* @return 影响行数
* @throws Exception
*/
public int del(Book book) throws Exception {
// 获得连接
Connection con = DBAccess.getConnection();
// sql语句
String sql="delete from t_mvc_book where bid = ? ";
// 执行sql语句
PreparedStatement ps = con.prepareStatement(sql);
// 给站位符赋值
ps.setObject(1, book.getBid());
// 返回影响行数
return ps.executeUpdate();
}
/**
* 修改
*@author ChenChen
* @since 2022.06.29
* @param book
* @return 影响行数
* @throws Exception
*/
public int edit(Book book) throws Exception {
// 获得连接
Connection con = DBAccess.getConnection();
// sql语句
String sql="update t_mvc_book set bname = ? , price = ? where bid = ? ";
// 执行sql语句
PreparedStatement ps = con.prepareStatement(sql);
// 给站位符赋值
ps.setObject(1, book.getBname());
ps.setObject(2, book.getPrice());
ps.setObject(3, book.getBid());
// 返回影响行数
return ps.executeUpdate();
}
}
写好之后,接下来就要测试dao方法了,建立测试类--- 【BookDaoTest.Class】
步骤:
之后会自动生成一个测试类 并且继续在里面编码 例如:
BookDaoTest.Class
代码块展示:
package com.chenchen.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.chenchen.entity.Book;
import com.chenchen.util.PageBean;
/**
* 测试类
* @author ChenChen
*@date 2022年6月29日 上午10:38:34
*/
public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testList() {
try {
List<Book> list = bookDao.list(new Book(),new PageBean());
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(123456421, "3333", 123);
try {
bookDao.add(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testDel() {
Book book = new Book(12344321, "33323", 123);
try {
bookDao.del(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testEdit() {
Book book = new Book(123456421, "吴彦祖", 123);
try {
bookDao.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
再利用JUnit Test进行测试:
然后进入数据库进行验证就好啦!
三、通用的增删改
优化上面的BookDao.Class,创建一个BaseDao.Class
BaseDao.Class
代码展示:
package com.chenchen.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.print.attribute.standard.PagesPerMinute;
import com.chenchen.entity.Book;
import com.chenchen.util.CallBack;
import com.chenchen.util.DBAccess;
import com.chenchen.util.PageBean;
import com.chenchen.util.StringUtils;
/**
* T代表的实体类,可以是Book/User/Goods...
*
* @author ChenChen
* @date 2022年6月23日 下午3:55:18
* @param <T>
*/
public class BaseDao<T> {
public List<T> executeQuery(String sql, PageBean pageBean, CallBack<T> callBack) throws Exception {
/**
* 1.拿到数据库连接 2.拿到Prepparestatement 3.执行sql语句
*/
Connection con = null;// 获得连接 重复代码1
PreparedStatement ps = null;// 执行sql语句 重复代码2
ResultSet rs = null;// 获得结果集 重复代码3
if (pageBean != null && pageBean.isPagination()) {// 判断pageBean不为空且 为true
String countSQL = getCountSQL(sql);
con = DBAccess.getConnection();// 获得连接 重复代码1
ps = con.prepareStatement(countSQL);// 执行sql语句 重复代码2
rs = ps.executeQuery();// 获得结果集 重复代码3
if (rs.next()) {
// 当前实体类就包含了总记录数
pageBean.setTotal(rs.getString("n"));
}
String pageSQL = getPageSQL(sql, pageBean);
System.out.println(pageSQL);
con = DBAccess.getConnection();// 获得连接 重复代码1
ps = con.prepareStatement(pageSQL);// 执行sql语句 重复代码2
rs = ps.executeQuery();// 获得结果集 重复代码3
} else {// 部分页的时候
con = DBAccess.getConnection();// 获得连接 重复代码1
ps = con.prepareStatement(sql);// 执行sql语句 重复代码2
rs = ps.executeQuery();// 获得结果集 重复代码3
}
return callBack.foreach(rs);
}
/**
* 拼装第N页的数据的SQL
*
* @author ChenChen
* @since 2022.06.24
* @param sql
* @return
*/
private String getPageSQL(String sql, PageBean pageBean) {
return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows();
}
/**
* 拼装符合条件总记录数的SQL
*
* @author ChenChen
* @since 2022.06.24
* @param sql
* @return
*/
private String getCountSQL(String sql) {
// sql=select * from t_mvc_book where bname like '%圣墟%'
// 从上面得到select count(1) as n from(select * from t_mvc_book where bname like
// '%圣墟%') t
// 目的是为了得到总记录数-->得到总页数
return "select count(1) as n from (" + sql + ") t";
}
public int executeUpdate(String sql,T t,String[] attrs) throws Exception {
Connection con = DBAccess.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
// 将 t 的某一个属性对应值加到 ps 对象中 拿到bid、bname、price
for (int i = 0; i < attrs.length; i++) {
// 通过类类拿到属性所对应的对象
Field f = t.getClass().getDeclaredField(attrs[i]);
// 打开访问权限
f.setAccessible(true);
//用对象.get属性获取属性值
ps.setObject(i + 1, f.get(t));
}
// ps.setObject(2, book.getBname());
// ps.setObject(3, book.getPrice());
return ps.executeUpdate();
}
}
优化后的BookDao.Class
代码展示:
package com.chenchen.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.chenchen.entity.Book;
import com.chenchen.util.BaseDao;
import com.chenchen.util.DBAccess;
import com.chenchen.util.PageBean;
import com.chenchen.util.StringUtils;
/**
* 数据库访问层
* @author ChenChen
*@date 2022年6月29日 上午10:26:03
*/
public class BookDao extends BaseDao<Book>{
// 查询
public List<Book> list(Book book,PageBean pageBean) throws Exception{
String sql = "select * from t_mvc_book 1=1 ";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +=" and banem 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<Book>();
// 处理结果集
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;
});//回调函数主要使用来处理我们的结果集
}
/**
* 增加
*@author ChenChen
* @since 2022.06.29
* @param book
* @return 影响行数
* @throws Exception
*/
public int add(Book book) throws Exception {
// sql语句
String sql="insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
}
/**
* 删除
*@author ChenChen
* @since 2022.06.29
* @param book
* @return 影响行数
* @throws Exception
*/
public int del(Book book) throws Exception {
// sql语句
String sql="delete from t_mvc_book where bid = ? ";
return super.executeUpdate(sql, book, new String[] {"bid"});
}
/**
* 修改
*@author ChenChen
* @since 2022.06.29
* @param book
* @return 影响行数
* @throws Exception
*/
public int edit(Book book) throws Exception {
// sql语句
String sql="update t_mvc_book set bname = ? , price = ? where bid = ? ";
return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
}
}
三、写主界面功能
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 引入我们自己写的标签库 -->
<%@taglib uri="http://zq.com" prefix="z" %>
<!-- 引入c标签 -->
<%@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>书籍列表</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>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=preEdit">新增</a>
</form>
<table class="table table-striped bg-success">
<thead>
<tr>
<th scope="col">书籍ID</th>
<th scope="col">书籍名</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=preEdit&bid=${b.bid}">编辑</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<z:page pageBean="${PageBean }"></z:page>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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 }">
bname:<input type="text" name="bname" value="${b.bname }">
price:<input type="text" name="price" value="${b.price }">
<input type="submit">
</form>
</body>
</html>