目录
一、将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
一、将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
将Framework包导成jar包
搜索框搜索jar
选中JAR File,然后点击下一步
红色区域选择路径,点击finish![](https://img-blog.csdnimg.cn/0214a5ad8ce84de8b3de5b718e3f36fb.png)
直接点击Ok就可以了![](https://img-blog.csdnimg.cn/c31476ad44044844a09ebec2c8e83146.png)
将相关依赖的jar包导入
二、将分页标签相关文件、及相关助手类导入
将博主之前所写的通用分页文章中util工具包和tag标签导入
三、完成Book实体类及bookdao的编写
package com.zwc.entity;
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;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
Bookdao(基础的增删改)
package com.zwc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.zwc.entity.Book;
import com.zwc.util.BaseDao;
import com.zwc.util.DBAccess;
import com.zwc.util.PageBean;
import com.zwc.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) {
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();
}
}
四、完成通用的增删改方法
大家可以发现上面基础的增删改代码都有一些相同代码
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
pst.setObject(1, book.getBname());
pst.setObject(2, book.getPrice());
pst.setObject(3, book.getBid());
所以我们要把它写成一个通用增删改
因为我们bookdao继承了basedao
basedao:
package com.zwc.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 com.zwc.entity.Book;
/**
* T代表实体类,可以是book/User/Goods...
* @author Administrator
*
* @param <T>
*/
public class BaseDao<T> {
// public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
sql="select * from t_mvc_book WHERE bname like '%圣墟%'";
从上面得到select COUNT(1) as n from (select * from t_mvc_book WHERE bname like '%圣墟%') t;
目的是为了得到总记录数->得到总页数
// select * from t_mvc_book WHERE bname like '%圣墟%' LIMIT 10,10;
//
// /**
// * 1、拿到数据库连接
// * 2、拿到preparestatement
// * 3、执行sql语句
// */
// Connection con = DBAccess.getConnection();//重复代码1
// PreparedStatement pst = con.prepareStatement(sql);//重复代码2
// ResultSet rs = pst.executeQuery();//重复代码3
while(rs.next()) {
list.add(new Book(rs.getInt("bid"), rs.getString("bname"),rs.getFloat("price") ));
}
查询不同表,必然要处理不同的结果集
接口是调用方来实现
// return callBack.foreach(rs);
// }
public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
/**
* 1、拿到数据库连接
* 2、拿到preparestatement
* 3、执行sql语句
*/
Connection con = null;//重复代码1
PreparedStatement pst = null;//重复代码2
ResultSet rs = null;//重复代码3
if(pageBean !=null && pageBean.isPagination()) {
String countSQL = getCountSQL(sql);
con = DBAccess.getConnection();
pst = con.prepareStatement(countSQL);
rs = pst.executeQuery();
if(rs.next()) {
// 当前实体类就包含了记录数
pageBean.setTotal(rs.getString("n"));
}
String pageSQL = getPageSQL(sql,pageBean);
con = DBAccess.getConnection();
pst = con.prepareStatement(pageSQL);
rs = pst.executeQuery();
}
else {
con = DBAccess.getConnection();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
}
// 查询不同表,必然要处理不同的结果集
// 接口是调用方来实现
return callBack.foreach(rs);
}
/**
* 拼装第n页的数据的sql
* @param sql
* @param pageBean
* @return
*/
private String getPageSQL(String sql, PageBean pageBean) {
return sql + " limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* 拼装符合条件总记录数的sql
* @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 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();
}
}
Bookdao :
package com.zwc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.zwc.entity.Book;
import com.zwc.util.BaseDao;
import com.zwc.util.DBAccess;
import com.zwc.util.PageBean;
import com.zwc.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) {
e.printStackTrace();
}
return list;
});
}
// 增
public int add(Book book) throws Exception {
String sql="insert into t_mvc_book values(?,?,?)";
// super调用basedao最后一个方法
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"});
}
}
五、完成BookAction
BookAction:
package com.zwc.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zwc.dao.BookDao;
import com.zwc.entity.Book;
import com.zwc.framework.ActionSupport;
import com.zwc.framework.ModelDrivetr;
import com.zwc.util.PageBean;
public class BookAction extends ActionSupport implements ModelDrivetr<Book>{
private Book b = new Book();
private BookDao book = new BookDao();
@Override
public Book getModel() {
return b;
}
// 增
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
book.add(b);
} catch (Exception e) {
e.printStackTrace();
}
// tolist代表跳到查询方法
return "toList";
}
// 删
public String del(HttpServletRequest req, HttpServletResponse resp) {
try {
book.del(b);
} catch (Exception e) {
e.printStackTrace();
}
// tolist代表跳到查询方法
return "toList";
}
// 修改
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
book.edit(b);
} catch (Exception e) {
e.printStackTrace();
}
// tolist代表跳到查询方法
return "toList";
}
// 查询
public String list(HttpServletRequest req, HttpServletResponse resp) {
try {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Book> list = book.list(b, 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 = b.getBid();
if(bid!=0) {
// 传递bid到后台,有且只能查出一条数据,那也就意味着list集合中只有一条
List<Book> list = book.list(b, null);
req.setAttribute("b", list.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
// tolist代表跳到编辑方法
return "toEdit";
}
}
六.xml的配置
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>T280_recf</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.zwc.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>configLocation</param-name>
<param-value>/zwc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
XML配置
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.zwc.web.BookAction">
<forward name="list" path="/bookList.jsp" redirect="false" />
<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
<forward name="toList" path="/book.action?methodName=list" redirect="true" />
</action>
</config>
七、前台代码的编写
主界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="z" uri="http://jsp.zwcedu.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="请输入书籍名称">
</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>
<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>
<a href="${pageContext.request.contextPath }/book.action?methodName=preEdit">新增</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 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>
<center>
<form action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
编号:<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}">
<input type="submit" value="提交">
</form>
</center>
</body>
</html>
主界面效果图:
点击编辑进入编辑界面,点击提交
在主界面可以看到已经改了
点击增加到增加页面点击提交
主界面展示
点击删除,编号为28的数据