目录
一、配置步骤
二、配置框架前三步
导入相应的jar
导入相应的Class
导入xml文件
三、优化基本操作(增删改)
1、基础优化
编写实体类
编写BookDao类
优化BookDao
JUnit测试
2、后台优化
3、前端优化
一、配置步骤
- 将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去
- 将分页标签相关文件、及相关助手类导入
- 框架的配置文件添加、以及web.xml的配置-以后开源框架的使用从这一步开始
- 完成Book实体类及bookDao的编写
- 完成通用的增删改方法
- 完成BookAction
- 完成mvc.xml的配置
- 完成前台代码的编写
二、配置框架前三步
导入相应的jar
导入之后我们选中所有的jar包===》右键===》Build Path===》Add to Build Path
导入相应的Class
导入xml文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.tgq.web.BookAction">
<forward name="list" path="/bookList.jsp" redirect="false" />
<forward name="toList" path="/book.action?methodName=list"
redirect="true" />
<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
</action>
</config>
测试我们的数据库能否连接
三、优化基本操作(增删改)
1、基础优化
编写实体类
package com.tgq.entity;
/**
* 实体类
*
* @author tgq
*
*/
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;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
// TODO Auto-generated constructor stub
}
}
编写BookDao类
编写增删改查的方法
package com.tgq.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import com.tgq.entity.Book;
import com.tgq.util.BaseDao;
import com.tgq.util.DBAccess;
import com.tgq.util.PageBean;
import com.tgq.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();
int bid = book.getBid();
// 判断是否为空
if (StringUtils.isNotBlank(bname)) {
sql += " and bname like '%" + bname + "%'";
}
// 判断前台是否传bid
if (bid != 0) {
sql += " and bid=" + bid;
}
return super.executeQuery(sql, Book.class, pageBean);
}
/**
* 增加Book的方法
*
* @param book
* 实体类
* @return
* @throws Exception
* 万能异常
*/
public int addBook(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBid());
ps.setObject(2, book.getBname());
ps.setObject(3, book.getPrice());
return ps.executeUpdate();
}
/**
* 删除Book的方法 ,根据id删除
*
* @param book
* 实体类
* @return
* @throws Exception
* 万能异常
*/
public int delBook(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid=?";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBid());
return ps.executeUpdate();
}
/**
* 修改Book的方法
*
* @param book
* 实体类
* @return
* @throws Exception
* 万能异常
*/
public int updateBook(Book book) throws Exception {
String sql = "update t_mvc_book set bname=?,price=? where bid=?";
Connection conn = DBAccess.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, book.getBname());
ps.setObject(2, book.getPrice());
ps.setObject(3, book.getBid());
return ps.executeUpdate();
}
}
1、在增删改的方法里面我们这两行代码是一样的、重复的
Connection conn = DBAccess.getConnection(); PreparedStatement ps = conn.prepareStatement(sql);
2、代码逻辑是重复的===》sql占位符赋值
ps.setObject(1, book.getBid()); ps.setObject(2, book.getBname()); ps.setObject(3, book.getPrice());
怎么解决?BaseDao
进行一个通用的增删改的方法/** * 通用的增删改方法 * * @param sql * 数据库sql语句 * @param t * 对应表的实体类 * @param attrs * 要修改的属性值 * @return * @throws Exception * 万能异常 */ public int executeUpdate(String sql, T t, String[] attrs) throws Exception { Connection conn = DBAccess.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); //利用fori 下标来进行?的赋值 for (int i = 0; i < attrs.length; i++) { Field field = t.getClass().getDeclaredField(attrs[i]); // 打开权限 field.setAccessible(true); ps.setObject(i + 1, field.get(t)); } return ps.executeUpdate(); }
优化BookDao
我们在BaseDao类里面增加了一个通用的增删改的方法,我们在BookDao里面利用起来
/**
* 增加Book的方法
*
* @param book
* 实体类
* @return
* @throws Exception
* 万能异常
*/
public int addBook(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
return super.executeUpdate(sql, book, new String[] { "bid", "bname", "price" });
}
/**
* 删除Book的方法 ,根据id删除
*
* @param book
* 实体类
* @return
* @throws Exception
* 万能异常
*/
public int delBook(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, book, new String[] { "bid" });
}
/**
* 修改Book的方法
*
* @param book
* 实体类
* @return
* @throws Exception
* 万能异常
*/
public int updateBook(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" });
}
JUnit测试
选中我们的类名===》ctrl+N===》JUnit Test Case===》选中顶部的New JUnit 4 test===》Next
勾选BookDao===》Finish
BookDaoTest测试
package com.tgq.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import com.tgq.entity.Book;
import com.tgq.util.PageBean;
public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Test
public void testList() throws Exception {
Book book = new Book();
book.setBname("52");
PageBean pageBean = new PageBean();
// pageBean.setPage(2);
List<Book> list = bookDao.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testAddBook() throws Exception {
Book book = new Book();
book.setBid(52);
book.setBname("5252");
book.setPrice(12f);
bookDao.addBook(book);
}
@Test
public void testDelBook() throws Exception {
Book book = new Book();
book.setBid(52);
bookDao.delBook(book);
}
@Test
public void testUpdateBook() throws Exception {
Book book = new Book();
book.setBid(52);
book.setBname("5252");
book.setPrice(19f);
bookDao.updateBook(book);
}
}
测试结果:
2、后台优化
我们新建一个web包,在里面新建一个BookAction类(class),继承ActionSupport,实现
ModelDriver接口,编写
package com.tgq.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tgq.dao.BookDao;
import com.tgq.entity.Book;
import com.tgq.util.PageBean;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
public class BookAction extends ActionSupport implements ModelDriver<Book> {
private Book book = new Book();
private BookDao bookDao = new BookDao();
// 查询 bookList.jsp
public String list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Book> list = bookDao.list(book, pageBean);
req.setAttribute("list", list);
req.setAttribute("pageBean", pageBean);
return "list";
}
// 编辑界面跳转 bookEdit.jsp
public String toEdit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
// 前提
if (book.getBid() != 0) {
List<Book> list = bookDao.list(book, null);// 不需要分页
req.setAttribute("b", list.get(0));
}
return "toEdit";
}
// 增加 重定向到book.action?methodName=list
public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
bookDao.addBook(book);
return "toEdit";
}
// 删除
public String del(HttpServletRequest req, HttpServletResponse resp) throws Exception {
bookDao.delBook(book);
return "toEdit";
}
// 修改
public String update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
bookDao.updateBook(book);
return "toEdit";
}
@Override
public Book getModel() {
return book;
}
}
我们编写jsp界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" 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>书籍列表</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="请输入书籍名称">
<!-- <input name="rows" value="20" type="hidden"> -->
<!-- 不想分页 -->
<input name="pagination" value="false" type="hidden">
</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=toEdit">新增</a>
</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 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}">修改</a>
<a
href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
增加,修改的jsp界面。
判断你点击的是否是增加还是修改
action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}"
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" 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>书籍新增/修改</title>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
书籍ID:<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 }"><br>
<input type="submit">
</form>
</body>
</html>
3、前端优化
我们运行书籍列表
进行一个搜索,新增、修改、删除
我们删除ID:16、22
新增一个
ID:12
书籍名:圣墟12
价格:123
修改ID:12
书籍名:圣墟1234
价格:12345
希望对你们有用!!!