书城项目-第五阶段:内容介绍、书城项目-MVC概念的介绍、书城项目-创建图书模块的数据库表、书城项目-编写图书模块的JavaBean类Book、书城项目-编写图书模块的Dao和测试、书城项目-编写图书模块的Service和测试、书城项目-图书列表功能的实现、书城项目-前后台的简单介绍、书城项目-添加图书功能实现、书城项目-删除图书功能的实现、书城项目-修改图书第一步,回显修改的信息、书城项目-修改图书第二步,提交给服务器保存修改
书城项目第五阶段-图书模块
尚硅谷书城项目
1、MVC 概念
MVC 全称:Model 模型、 View 视图、 Controller 控制器。
MVC 最早出现在 JavaEE 三层中的 Web 层,它可以有效的指导 Web 层的代码如何有效分离,单独工作。
View 视图:只负责数据和界面的显示,不接受任何与显示数据无关的代码,便于程序员和美工的分工合作——JSP/HTML。
Controller 控制器:只负责接收请求,调用业务层的代码处理请求,然后派发页面,是一个“调度者”的角色——Servlet。
转到某个页面。或者是重定向到某个页面。
Model 模型:将与业务逻辑相关的数据封装为具体的 JavaBean 类,其中不掺杂任何与数据处理相关的代码——JavaBean/domain/entity/pojo。
MVC 是一种思想
MVC 的理念是将软件代码拆分成为组件,单独开发,组合使用(目的还是为了降低耦合度)。
MVC 的作用还是为了降低耦合。让代码合理分层。方便后期升级和维护。
书城第五阶段
1、图书模块
1.1、编写图书模块的数据库表
# P233 书城项目-创建图书模块的数据库表
CREATE TABLE t_book(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100), #名称
price DECIMAL(11,2), #价格
author VARCHAR(100), #作者
sales INT, #销量
stock INT, #库存
img_path VARCHAR(200) #图片
);
# 插入初始化测试数据
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'java从入门到放弃' , '国哥' , 80 , 9999 , 9 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '数据结构与算法' , '严敏君' , 78.5 , 6 , 13 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '怎样拐跑别人的媳妇' , '龙伍' , 68, 99999 , 52 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '木虚肉盖饭' , '小胖' , 16, 1000 , 50 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'C++编程思想' , '刚哥' , 45.5 , 14 , 95 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '蛋炒饭' , '周星星' , 9.9, 12 , 53 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '赌神' , '龙伍' , 66.5, 125 , 535 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'Java编程思想' , '阳哥' , 99.5 , 47 , 36 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'JavaScript从入门到精通' , '婷姐' , 9.9 , 85 , 95 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'cocos2d-x游戏编程入门' , '国哥' , 49, 52 , 62 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'C语言程序设计' , '谭浩强' , 28 , 52 , 74 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'Lua语言程序设计' , '雷丰阳' , 51.5 , 48 , 82 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '西游记' , '罗贯中' , 12, 19 , 9999 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '水浒传' , '华仔' , 33.05 , 22 , 88 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '操作系统原理' , '刘优' , 133.05 , 122 , 188 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '数据结构 java版' , '封大神' , 173.15 , 21 , 81 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'UNIX高级环境编程' , '乐天' , 99.15 , 210 , 810 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , 'javaScript高级编程' , '国哥' , 69.15 , 210 , 810 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '大话设计模式' , '国哥' , 89.15 , 20 , 10 , 'static/img/default.jpg');
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` , `img_path`)
values(null , '人月神话' , '刚哥' , 88.15 , 20 , 80 , 'static/img/default.jpg');
# 查看表内容
select id,name,author,price,sales,stock,img_path from t_book;
1.2、编写图书模块的 JavaBean
package top.qaqaq.pojo;
import java.math.BigDecimal;
/**
* @author RichieZhang
* @create 2022-12-10 下午 5:22
*/
public class Book {
private Integer id;
private String name; //名称
private String author; //作者
private BigDecimal price; //价格
private Integer sales; //销量
private Integer stock; //库存
private String imgpath = "static/img/default.jpg"; //图片
public Book() {
}
public Book(Integer id, String name, String author, BigDecimal price, Integer sales, Integer stock, String imgpath) {
this.id = id;
this.name = name;
this.author = author;
this.price = price;
this.sales = sales;
this.stock = stock;
// 要求给定的图书封面图书路径不能为空
if (imgpath != null && !"".equals(imgpath)){
this.imgpath = imgpath;
}
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public String getImgpath() {
return imgpath;
}
public void setImgpath(String imgpath) {
// 要求给定的图书封面图书路径不能为空
if (imgpath != null && !"".equals(imgpath)){
this.imgpath = imgpath;
}
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
", sales=" + sales +
", stock=" + stock +
", imgpath='" + imgpath + '\'' +
'}';
}
}
1.3、编写图书模块的 Dao 和测试 Dao
Dao 接口
package top.qaqaq.dao;
import top.qaqaq.pojo.Book;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 5:36
*/
public interface BookDao {
/**
* 添加图书
* @param book
* @return
*/
public int addBook(Book book);
/**
* 根据图书id删除图书
* @param id
* @return
*/
public int deleteBookById(Integer id);
/**
* 根据图书id更新图书
* @param book
* @return
*/
public int updateBook(Book book);
/**
* 根据图书id查询图书
* @param id
* @return
*/
public Book queryBookById(Integer id);
/**
* 查询全部图书
* @return
*/
public List<Book> queryBooks();
}
BookDaoImpl 实现类:
package top.qaqaq.dao.impl;
import top.qaqaq.dao.BookDao;
import top.qaqaq.pojo.Book;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 5:40
*/
public class BookDaoImpl extends BaseDao implements BookDao {
@Override
public int addBook(Book book) {
String sql = "insert into t_book(name,author,price,sales,stock,img_path) values(?,?,?,?,?,?)";
return update(sql, book.getName(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(), book.getImgpath());
}
@Override
public int deleteBookById(Integer id) {
String sql = "delete from t_book where id = ?";
return update(sql, id);
}
@Override
public int updateBook(Book book) {
String sql = "update t_book set name=?,author=?,price=?,sales=?,stock=?,img_path=? where id = ?";
return update(sql, book.getName(), book.getAuthor(), book.getPrice(), book.getSales(), book.getStock(), book.getImgpath(), book.getId());
}
@Override
public Book queryBookById(Integer id) {
String sql = "select id,name,author,price,sales,stock,img_path imgpath from t_book where id = ?";
return queryForOne(Book.class, sql, id);
}
@Override
public List<Book> queryBooks() {
String sql = "select id,name,author,price,sales,stock,img_path imgpath from t_book";
return queryForList(Book.class, sql);
}
}
BookDao 的测试:
package top.qaqaq.test;
import org.junit.Test;
import top.qaqaq.dao.BookDao;
import top.qaqaq.dao.impl.BookDaoImpl;
import top.qaqaq.pojo.Book;
import java.math.BigDecimal;
/**
* @author RichieZhang
* @create 2022-12-10 下午 5:54
*/
public class BookDaoTest {
private BookDao bookDao = new BookDaoImpl();
@Test
public void addBook() {
bookDao.addBook(new Book(null,"我为什么这么帅!","191125",new BigDecimal(9999),1100000,0,null));
}
@Test
public void deleteBookById() {
bookDao.deleteBookById(21);
}
@Test
public void updateBook() {
bookDao.updateBook(new Book(21,"大家都可以这么帅!","自己",new BigDecimal(9999),1100000,0,null));
}
@Test
public void queryBookById() {
System.out.println(bookDao.queryBookById(21));
}
@Test
public void queryBooks() {
bookDao.queryBooks().forEach(System.out::println);
}
}
1.4、编写图书模块的 Service 和测试 Service
BookService 接口
package top.qaqaq.service;
import top.qaqaq.pojo.Book;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:37
*/
public interface BookService {
/**
* 添加图书
* @param book
*/
public void addBook(Book book);
/**
* 根据图书id删除图书
* @param id
*/
public void deleteBookById(Integer id);
/**
* 根据图书id更新图书
* @param book
*/
public void updateBook(Book book);
/**
* 根据图书id查询图书
* @param id
* @return
*/
public Book queryBookById(Integer id);
/**
* 查询全部图书
* @return
*/
public List<Book> queryBooks();
}
BookServiceImpl 实现类:
package top.qaqaq.service.impl;
import top.qaqaq.dao.BookDao;
import top.qaqaq.dao.impl.BookDaoImpl;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:42
*/
public class BookServiceImpl implements BookService {
private BookDao bookDao = new BookDaoImpl();
@Override
public void addBook(Book book) {
bookDao.addBook(book);
}
@Override
public void deleteBookById(Integer id) {
bookDao.deleteBookById(id);
}
@Override
public void updateBook(Book book) {
bookDao.updateBook(book);
}
@Override
public Book queryBookById(Integer id) {
return bookDao.queryBookById(id);
}
@Override
public List<Book> queryBooks() {
return bookDao.queryBooks();
}
}
BookService 的测试:
package top.qaqaq.test;
import org.junit.Test;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import top.qaqaq.service.impl.BookServiceImpl;
import java.math.BigDecimal;
import static org.junit.Assert.*;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:45
*/
public class BookServiceTest {
private BookService bookService = new BookServiceImpl();
@Test
public void addBook() {
bookService.addBook(new Book(null,"你好我好大家好","1125",new BigDecimal(100000),10000000,0,null));
}
@Test
public void deleteBookById() {
bookService.deleteBookById(22);
}
@Test
public void updateBook() {
bookService.updateBook(new Book(22,"大家好","1125",new BigDecimal(999999),10,1000000,null));
}
@Test
public void queryBookById() {
System.out.println(bookService.queryBookById(22));
}
@Test
public void queryBooks() {
bookService.queryBooks().forEach(System.out::println);
}
}
1.5、编写图书模块的 Web 层,和页面联调测试
1.5.1、图书列表功能的实现
1、图解列表功能流程:
2、BookServlet 程序中添加 list 方法
package top.qaqaq.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import top.qaqaq.service.impl.BookServiceImpl;
import java.io.IOException;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:51
*/
public class BookServlet extends BaseServlet {
private BookService bookService = new BookServiceImpl();
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
}
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
}
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
}
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 通过BookService查询全部图书
List<Book> books = bookService.queryBooks();
// 2. 把全部图书保存到Request域中
req.setAttribute("books", books);
// 3. 请求转发到/pages/manager/book_manager.jsp页面
req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
}
}
3、修改【图书管理】请求地址
<%--
Created by IntelliJ IDEA.
User: ZRich
Date: 2022/12/9
Time: 下午 5:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<div>
<%-- action=list表示调用BookServlet.java里的list方法 --%>
<a href="manager/bookServlet?action=list">图书管理</a>
<a href="pages/manager/order_manager.jsp">订单管理</a>
<a href="index.jsp">返回商城</a>
</div>
4、修改 pages/manager/book_manager.jsp 页面的数据遍历输出
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理</title>
<%-- 静态包含 base标签,css样式,jQuery文件 --%>
<%@ include file="/pages/common/head.jsp"%>
</head>
<body>
<div id="header">
<img class="logo_img" alt="" src="../../static/img/logo.gif" >
<span class="wel_word">图书管理系统</span>
<%-- 静态包含 manager 管理模块的菜单 --%>
<%@include file="/pages/common/manager_menu.jsp"%>
</div>
<div id="main">
<table>
<tr>
<td>名称</td>
<td>价格</td>
<td>作者</td>
<td>销量</td>
<td>库存</td>
<td colspan="2">操作</td>
</tr>
<c:forEach items="${requestScope.books}" var="book">
<tr>
<td>${book.name}</td>
<td>${book.price}</td>
<td>${book.author}</td>
<td>${book.sales}</td>
<td>${book.stock}</td>
<td><a href="book_edit.jsp">修改</a></td>
<td><a href="#">删除</a></td>
</tr>
</c:forEach>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="book_edit.jsp">添加图书</a></td>
</tr>
</table>
</div>
<%-- 静态包含页脚内容 --%>
<%@include file="/pages/common/footer.jsp"%>
</body>
</html>
1.5.2、前后台的简单介绍
1.5.3、添加图书功能的实现
1.5.3.1、添加图书流程细节:
1.5.3.2、问题说明:表单重复提交:
当用户提交完请求,浏览器会记录下最后一次请求的全部信息。当用户按下功能键 F5,就会发起浏览器记录的最后一次请求。
1.5.3.3、BookServlet 程序中添加 add 方法
package top.qaqaq.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import top.qaqaq.service.impl.BookServiceImpl;
import top.qaqaq.utils.WebUtils;
import java.io.IOException;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:51
*/
public class BookServlet extends BaseServlet {
private BookService bookService = new BookServiceImpl();
/**
* 负责添加图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.addBook()保存图书
bookService.addBook(book);
// 3. 跳到图书列表页面
// /manager/bookServlet?action=list
// 如果使用请求转发,则为一次请求,刷新会重复提交数据
// req.getRequestDispatcher("/manager/bookServlet?action=list").forward(req,resp);
// 所以使用请求重定向
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 负责删除图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数id,图书编程
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.deleteBookById();删除图书
bookService.deleteBookById(id);
// 3. 重定向回图书列表管理页面
// /book/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 保存修改图书的操作
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.updateBook( book );修改图书
bookService.updateBook(book);
// 3. 重定向回图书列表管理页面
// 地址:/工程名/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 获取要修改的图书信息
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数图书编号
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.queryBookById查询图书
Book book = bookService.queryBookById(id);
// 3. 保存图书到Request域中
req.setAttribute("book",book);
// 4. 请求转发到。pages/manager/book_edit.jsp页面
req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
}
/**
* 负责遍历图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 通过BookService查询全部图书
List<Book> books = bookService.queryBooks();
// 2. 把全部图书保存到Request域中
req.setAttribute("books", books);
// 3. 请求转发到/pages/manager/book_manager.jsp页面
req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
}
}
1.5.3.4、修改 book_edit.jsp 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>编辑图书</title>
<%-- 静态包含 base标签,css样式,jQuery文件 --%>
<%@ include file="/pages/common/head.jsp"%>
<style type="text/css">
h1 {
text-align: center;
margin-top: 200px;
}
h1 a {
color:red;
}
input {
text-align: center;
}
</style>
</head>
<body>
<!--
遇到的问题:
book_edit.jsp页面,既要做添加操作。又要做修改操作,而到底是添加,还是修改是由一个隐藏域来决定的。
如何动态修改隐藏域<input type="hidden" name="action" value="xxx" /> 让它的值既可以实现添加,又可以实现修改操作?
//方案一:
可以当请求发起时,附带上当前要操作的值。并注入到隐藏域中。
//方案二:
可以通过判断当前请求参数中是否包含有id参数。如果有说明是修改操作。如果没有说明是添加操作。
是否是添加操作:
<%-- ${ empty param.id ? "add" : "update"}--%>
//方案三:
可以通过判断,Request域中是否包含有修改的图书信息对象,如果没有说明是添加操作。如果有说明是修改操作。
是否是添加操作:
<%-- ${ empty requestScope.book ? "add" : "update"}--%>
-->
<div id="header">
<img class="logo_img" alt="" src="../../static/img/logo.gif" >
<span class="wel_word">编辑图书</span>
<%-- 静态包含 manager 管理模块的菜单 --%>
<%@include file="/pages/common/manager_menu.jsp"%>
</div>
<div id="main">
<form action="manager/bookServlet" method="get">
<input type="hidden" name="action" value="${ empty param.id ? "add" : "update"}" />
<input type="hidden" name="id" value="${requestScope.book.id}" />
<table>
<tr>
<td>名称</td>
<td>价格</td>
<td>作者</td>
<td>销量</td>
<td>库存</td>
<td colspan="2">操作</td>
</tr>
<tr>
<td><input name="name" type="text" value="${requestScope.book.name}"/></td>
<td><input name="price" type="text" value="${requestScope.book.price}"/></td>
<td><input name="author" type="text" value="${requestScope.book.author}"/></td>
<td><input name="sales" type="text" value="${requestScope.book.sales}"/></td>
<td><input name="stock" type="text" value="${requestScope.book.stock}"/></td>
<td><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</div>
<%-- 静态包含页脚内容 --%>
<%@include file="/pages/common/footer.jsp"%>
</body>
</html>
1.5.4、删除图书功能的实现
1.5.4.1、图解删除流程:
1.5.4.2、BookServlet 程序中的 delete 方法:
package top.qaqaq.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import top.qaqaq.service.impl.BookServiceImpl;
import top.qaqaq.utils.WebUtils;
import java.io.IOException;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:51
*/
public class BookServlet extends BaseServlet {
private BookService bookService = new BookServiceImpl();
/**
* 负责添加图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.addBook()保存图书
bookService.addBook(book);
// 3. 跳到图书列表页面
// /manager/bookServlet?action=list
// 如果使用请求转发,则为一次请求,刷新会重复提交数据
// req.getRequestDispatcher("/manager/bookServlet?action=list").forward(req,resp);
// 所以使用请求重定向
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 负责删除图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数id,图书编程
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.deleteBookById();删除图书
bookService.deleteBookById(id);
// 3. 重定向回图书列表管理页面
// /book/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 保存修改图书的操作
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.updateBook( book );修改图书
bookService.updateBook(book);
// 3. 重定向回图书列表管理页面
// 地址:/工程名/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 获取要修改的图书信息
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数图书编号
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.queryBookById查询图书
Book book = bookService.queryBookById(id);
// 3. 保存图书到Request域中
req.setAttribute("book",book);
// 4. 请求转发到。pages/manager/book_edit.jsp页面
req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
}
/**
* 负责遍历图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 通过BookService查询全部图书
List<Book> books = bookService.queryBooks();
// 2. 把全部图书保存到Request域中
req.setAttribute("books", books);
// 3. 请求转发到/pages/manager/book_manager.jsp页面
req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
}
}
1.5.4.3、给 WebUtils 工具类添加转换 int 类型的工具方法
package top.qaqaq.utils;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @author RichieZhang
* @create 2022-12-10 下午 2:11
*/
public class WebUtils {
/**
* 把Map中的值注入到对应的JavaBean属性中。
* @param value
* @param bean
* 如果形参写成HttpServletRequest DAO层和Service层没有这个API 且web层耦合度高,代码不优雅
* DAO层
* Service层
* Web层
*/
public static <T> T copyParamToBean(Map value, T bean) {
try {
System.out.println("注入之前:" + bean);
BeanUtils.populate(bean,value);
System.out.println("注入之后:" + bean);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
/**
* 将字符串转换成为int类型
* @param strInt
* @param defaultValue
* @return
*/
public static int parseInt(String strInt, int defaultValue){
try {
return Integer.parseInt(strInt);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return defaultValue;
}
}
1.5.4.4、修改删除的连接地址:
book_manager.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理</title>
<%-- 静态包含 base标签,css样式,jQuery文件 --%>
<%@ include file="/pages/common/head.jsp"%>
<script type="text/javascript">
$(function () {
// 给删除的a标签绑定单击事件,用于删除的确认提示操作
$("a.deleteClass").click(function () {
//在事件的function函数中,有一个this对象。这个this对象,是当前正在响应事件的dom对象。
/**
* confirm是确认提示框函数
* 参数是它的提示内容
* 它有两个按钮,一个确认,一个取消。
* 返回true表示点击了,确认,返回false表示点击取消
*/
return confirm("你确定要删除【" + $(this).parent().parent().find("td:first").text() + "】?")
//return false// 阻止元素的默认行为===不提交请求
})
})
</script>
</head>
<body>
<div id="header">
<img class="logo_img" alt="" src="../../static/img/logo.gif" >
<span class="wel_word">图书管理系统</span>
<%-- 静态包含 manager 管理模块的菜单 --%>
<%@include file="/pages/common/manager_menu.jsp"%>
</div>
<div id="main">
<table>
<tr>
<td>名称</td>
<td>价格</td>
<td>作者</td>
<td>销量</td>
<td>库存</td>
<td colspan="2">操作</td>
</tr>
<c:forEach items="${requestScope.books}" var="book">
<tr>
<td>${book.name}</td>
<td>${book.price}</td>
<td>${book.author}</td>
<td>${book.sales}</td>
<td>${book.stock}</td>
<td><a href="manager/bookServlet?action=getBook&id=${book.id}">修改</a></td>
<td><a class="deleteClass" href="manager/bookServlet?action=delete&id=${book.id}">删除</a></td>
</tr>
</c:forEach>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="pages/manager/book_edit.jsp">添加图书</a></td>
</tr>
</table>
</div>
<%-- 静态包含页脚内容 --%>
<%@include file="/pages/common/footer.jsp"%>
</body>
</html>
1.5.4.5、给删除添加确认提示操作:
1.5.5、修改图书功能的实现
1.5.5.1:图解修改图书细节:
1.5.5.2、更新【修改】的请求地址:
book_manager.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理</title>
<%-- 静态包含 base标签,css样式,jQuery文件 --%>
<%@ include file="/pages/common/head.jsp"%>
<script type="text/javascript">
$(function () {
// 给删除的a标签绑定单击事件,用于删除的确认提示操作
$("a.deleteClass").click(function () {
//在事件的function函数中,有一个this对象。这个this对象,是当前正在响应事件的dom对象。
/**
* confirm是确认提示框函数
* 参数是它的提示内容
* 它有两个按钮,一个确认,一个取消。
* 返回true表示点击了,确认,返回false表示点击取消
*/
return confirm("你确定要删除【" + $(this).parent().parent().find("td:first").text() + "】?")
//return false// 阻止元素的默认行为===不提交请求
})
})
</script>
</head>
<body>
<div id="header">
<img class="logo_img" alt="" src="../../static/img/logo.gif" >
<span class="wel_word">图书管理系统</span>
<%-- 静态包含 manager 管理模块的菜单 --%>
<%@include file="/pages/common/manager_menu.jsp"%>
</div>
<div id="main">
<table>
<tr>
<td>名称</td>
<td>价格</td>
<td>作者</td>
<td>销量</td>
<td>库存</td>
<td colspan="2">操作</td>
</tr>
<c:forEach items="${requestScope.books}" var="book">
<tr>
<td>${book.name}</td>
<td>${book.price}</td>
<td>${book.author}</td>
<td>${book.sales}</td>
<td>${book.stock}</td>
<td><a href="manager/bookServlet?action=getBook&id=${book.id}">修改</a></td>
<td><a class="deleteClass" href="manager/bookServlet?action=delete&id=${book.id}">删除</a></td>
</tr>
</c:forEach>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="pages/manager/book_edit.jsp">添加图书</a></td>
</tr>
</table>
</div>
<%-- 静态包含页脚内容 --%>
<%@include file="/pages/common/footer.jsp"%>
</body>
</html>
1.5.5.3、BookServlet 程序中添加 getBook 方法:
package top.qaqaq.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import top.qaqaq.service.impl.BookServiceImpl;
import top.qaqaq.utils.WebUtils;
import java.io.IOException;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:51
*/
public class BookServlet extends BaseServlet {
private BookService bookService = new BookServiceImpl();
/**
* 负责添加图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.addBook()保存图书
bookService.addBook(book);
// 3. 跳到图书列表页面
// /manager/bookServlet?action=list
// 如果使用请求转发,则为一次请求,刷新会重复提交数据
// req.getRequestDispatcher("/manager/bookServlet?action=list").forward(req,resp);
// 所以使用请求重定向
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 负责删除图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数id,图书编程
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.deleteBookById();删除图书
bookService.deleteBookById(id);
// 3. 重定向回图书列表管理页面
// /book/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 保存修改图书的操作
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.updateBook( book );修改图书
bookService.updateBook(book);
// 3. 重定向回图书列表管理页面
// 地址:/工程名/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 获取要修改的图书信息
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数图书编号
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.queryBookById查询图书
Book book = bookService.queryBookById(id);
// 3. 保存图书到Request域中
req.setAttribute("book",book);
// 4. 请求转发到。pages/manager/book_edit.jsp页面
req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
}
/**
* 负责遍历图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 通过BookService查询全部图书
List<Book> books = bookService.queryBooks();
// 2. 把全部图书保存到Request域中
req.setAttribute("books", books);
// 3. 请求转发到/pages/manager/book_manager.jsp页面
req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
}
}
1.5.5.4、在 book_edit.jsp 页面中显示修改的数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>编辑图书</title>
<%-- 静态包含 base标签,css样式,jQuery文件 --%>
<%@ include file="/pages/common/head.jsp"%>
<style type="text/css">
h1 {
text-align: center;
margin-top: 200px;
}
h1 a {
color:red;
}
input {
text-align: center;
}
</style>
</head>
<body>
<!--
遇到的问题:
book_edit.jsp页面,既要做添加操作。又要做修改操作,而到底是添加,还是修改是由一个隐藏域来决定的。
如何动态修改隐藏域<input type="hidden" name="action" value="xxx" /> 让它的值既可以实现添加,又可以实现修改操作?
//方案一:
可以当请求发起时,附带上当前要操作的值。并注入到隐藏域中。
//方案二:
可以通过判断当前请求参数中是否包含有id参数。如果有说明是修改操作。如果没有说明是添加操作。
是否是添加操作:
<%-- ${ empty param.id ? "add" : "update"}--%>
//方案三:
可以通过判断,Request域中是否包含有修改的图书信息对象,如果没有说明是添加操作。如果有说明是修改操作。
是否是添加操作:
<%-- ${ empty requestScope.book ? "add" : "update"}--%>
-->
<div id="header">
<img class="logo_img" alt="" src="../../static/img/logo.gif" >
<span class="wel_word">编辑图书</span>
<%-- 静态包含 manager 管理模块的菜单 --%>
<%@include file="/pages/common/manager_menu.jsp"%>
</div>
<div id="main">
<form action="manager/bookServlet" method="get">
<input type="hidden" name="action" value="${ empty param.id ? "add" : "update"}" />
<input type="hidden" name="id" value="${requestScope.book.id}" />
<table>
<tr>
<td>名称</td>
<td>价格</td>
<td>作者</td>
<td>销量</td>
<td>库存</td>
<td colspan="2">操作</td>
</tr>
<tr>
<td><input name="name" type="text" value="${requestScope.book.name}"/></td>
<td><input name="price" type="text" value="${requestScope.book.price}"/></td>
<td><input name="author" type="text" value="${requestScope.book.author}"/></td>
<td><input name="sales" type="text" value="${requestScope.book.sales}"/></td>
<td><input name="stock" type="text" value="${requestScope.book.stock}"/></td>
<td><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</div>
<%-- 静态包含页脚内容 --%>
<%@include file="/pages/common/footer.jsp"%>
</body>
</html>
1.5.5.5、在 BookServlet 程序中添加 update 方法:
package top.qaqaq.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.qaqaq.pojo.Book;
import top.qaqaq.service.BookService;
import top.qaqaq.service.impl.BookServiceImpl;
import top.qaqaq.utils.WebUtils;
import java.io.IOException;
import java.util.List;
/**
* @author RichieZhang
* @create 2022-12-10 下午 7:51
*/
public class BookServlet extends BaseServlet {
private BookService bookService = new BookServiceImpl();
/**
* 负责添加图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.addBook()保存图书
bookService.addBook(book);
// 3. 跳到图书列表页面
// /manager/bookServlet?action=list
// 如果使用请求转发,则为一次请求,刷新会重复提交数据
// req.getRequestDispatcher("/manager/bookServlet?action=list").forward(req,resp);
// 所以使用请求重定向
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 负责删除图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数id,图书编程
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.deleteBookById();删除图书
bookService.deleteBookById(id);
// 3. 重定向回图书列表管理页面
// /book/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 保存修改图书的操作
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数==封装成为Book对象
Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
// 2. 调用BookService.updateBook( book );修改图书
bookService.updateBook(book);
// 3. 重定向回图书列表管理页面
// 地址:/工程名/manager/bookServlet?action=list
resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
/**
* 获取要修改的图书信息
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 获取请求的参数图书编号
int id = WebUtils.parseInt(req.getParameter("id"),0);
// 2. 调用bookService.queryBookById查询图书
Book book = bookService.queryBookById(id);
// 3. 保存图书到Request域中
req.setAttribute("book",book);
// 4. 请求转发到。pages/manager/book_edit.jsp页面
req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
}
/**
* 负责遍历图书
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
// 1. 通过BookService查询全部图书
List<Book> books = bookService.queryBooks();
// 2. 把全部图书保存到Request域中
req.setAttribute("books", books);
// 3. 请求转发到/pages/manager/book_manager.jsp页面
req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
}
}
1.5.5.6、解决 book_edit.jsp 页面,即要实现添加,又要实现修改操作。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!-- <servlet>-->
<!-- <servlet-name>RegistServlet</servlet-name>-->
<!-- <servlet-class>top.qaqaq.web.RegistServlet</servlet-class>-->
<!-- </servlet>-->
<!-- <servlet-mapping>-->
<!-- <servlet-name>RegistServlet</servlet-name>-->
<!-- <url-pattern>/registServlet</url-pattern>-->
<!-- </servlet-mapping>-->
<!-- <servlet>-->
<!-- <servlet-name>LoginServlet</servlet-name>-->
<!-- <servlet-class>top.qaqaq.web.LoginServlet</servlet-class>-->
<!-- </servlet>-->
<!-- <servlet-mapping>-->
<!-- <servlet-name>LoginServlet</servlet-name>-->
<!-- <url-pattern>/loginServlet</url-pattern>-->
<!-- </servlet-mapping>-->
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>top.qaqaq.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>top.qaqaq.web.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/manager/bookServlet</url-pattern>
</servlet-mapping>
</web-app>