二、 图书
分析实体
图书,单词为
Book
实体的名称就定义下来了|— 属性:
图书编号 bookId(用于确定的唯一性);
图书名称 bookName;
图书作者 author ;
图书单价 price ; 类型是 double
出版社 publish ;
图书封面 bookPic ;
库存 count 类型是 int
类目 category{ 类型: Category}
1.1 实体类:
1, 定义属性变量 2,使用快捷键Alt+Insert 生成getter和setter方法 3, 使用快捷键Alt+Insert 生成toString方法,便于打印查看具体数据 4,使用快捷键Alt+Insert 生成构造方法 4.1, 有参数的构造方法 4.2, 无参数的构造方法
package cn.javabs.entity; public class Book { private int bookId; private String bookName; private String publish;// 出版社 private double price; // 为什么不用float类型,因为默认就是double 、其次 使用float类型定义, 小数后需要添加f // 如float f1 = 6.5f private String author; private int count ; private String bookPic ; private Category category; public Book(int bookId, String bookName, String publish, double price, String author, int count, String bookPic, Category category) { this.bookId = bookId; this.bookName = bookName; this.publish = publish; this.price = price; this.author = author; this.count = count; this.bookPic = bookPic; this.category = category; } public Book(String bookName, String publish, double price, String author, int count, String bookPic, Category category) { this.bookName = bookName; this.publish = publish; this.price = price; this.author = author; this.count = count; this.bookPic = bookPic; this.category = category; } public Book() { super(); } @Override public String toString() { return "Book{" + "bookId=" + bookId + ", bookName='" + bookName + '\'' + ", publish='" + publish + '\'' + ", price=" + price + ", author='" + author + '\'' + ", count=" + count + ", bookPic='" + bookPic + '\'' + ", category=" + category + '}'; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getPublish() { return publish; } public void setPublish(String publish) { this.publish = publish; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getBookPic() { return bookPic; } public void setBookPic(String bookPic) { this.bookPic = bookPic; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
1.2 编写Service层
Service层有 接口和实现类
(1)先去编写接口,接口的命名规范为 [实体类的名称+ Service],本接口为BookService,实现类为BookServiceImpl
(2)考虑该接口内哪些功能,功能对应的是方法。
功能如下:
①增加图书
②删除图书
③修改图书
④查询所有图书
⑤根据类目查询图书
⑥根据图书名称查询图书详细信息
⑦根据图书编号查询图书
对应的是七个方法:
增加图书方法, 参数列表是:Book book; 返回值类型为int
删除图书方法, 参数列表是:int bookId; 返回值类型为int
修改图书方法, 参数列表是Book book; 返回值类型为int
查询所有图书方法, 无参数 返回值类型为List<Book>;
【因为查询的所有类目,不再是单一的一个类目,需要有容器存储所有类目对象,该容器合适的是集合,便于查询的是ArrayList集合。{ArrayList特性是 查询快、增删慢 | LinkedList特性是 查询慢、增删快}】
根据类目查询图书, 参数列表是Category category; 返回值类型为List<Book>;
根据图书名称查询图书, 参数列表是String bookName; 返回值类型为List<Book>;
根据图书编号查询图书,参数列表是:int bookId; 返回值类型为Book;
【因为查询的是一个类目,所有就是对象存储。】
代码如下:
package cn.javabs.service; import cn.javabs.entity.Book; import cn.javabs.entity.Category; import java.util.List; public interface BookService { int addBook(Book book); int delBook(int bookId); int editBook(Book book); List<Book> findAllBooks(); List<Book> findBookByCategory(Category category); List<Book> findBookByBookName(String bookName); Book findBookById(int bookId); }
BookServiceImpl实现类具体操作与上篇雷同,不再截图展示具体过程。
package cn.javabs.service.impl; import cn.javabs.dao.BookDao; import cn.javabs.dao.impl.BookDaoImpl; import cn.javabs.entity.Book; import cn.javabs.entity.Category; import cn.javabs.service.BookService; import java.util.List; public class BookServiceImpl implements BookService { BookDao bookDao = new BookDaoImpl(); @Override public int addBook(Book book) { return bookDao.add(book); } @Override public int delBook(int bookId) { return bookDao.del(bookId); } @Override public int editBook(Book book) { return bookDao.edit(book); } @Override public List<Book> findAllBooks() { return bookDao.getAllBooks(); } @Override public List<Book> findBookByCategory(Category category) { return bookDao.getBookByCategory(category); } @Override public List<Book> findBookByBookName(String bookName) { return bookDao.getBookByBookName(bookName); } @Override public Book findBookById(int bookId) { return bookDao.getBookById(bookId); } }
1.2 编写Dao层
Dao层有 接口和实现类
package cn.javabs.dao; import cn.javabs.entity.Book; import cn.javabs.entity.Category; import java.util.List; public interface BookDao { /** * 添加图书 * @param book * @return */ int add(Book book); /** * 删除图书 * @param bookId * @return */ int del(int bookId); /** * 修改图书 * @param book * @return */ int edit(Book book); /** * 查询所有图书 * @return */ List<Book> getAllBooks(); /** * 根据分类查询图书 * @param category * @return */ List<Book> getBookByCategory(Category category); /** * 根据图书名称查询图书 * @param bookName * @return */ List<Book> getBookByBookName(String bookName); /** * 根据图书编号查询图书 * @param bookId * @return */ Book getBookById(int bookId); }
package cn.javabs.dao.impl; import cn.javabs.dao.BookDao; import cn.javabs.entity.Book; import cn.javabs.entity.Category; import cn.javabs.util.DruidUtil; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.SQLException; import java.util.List; public class BookDaoImpl implements BookDao { QueryRunner qr = new QueryRunner(DruidUtil.getDataSource()); /** * 添加图书 * * @param book * @return */ @Override public int add(Book book) { try { return qr.update("insert into book(bookName,publish,price,author,count,bookPic,categoryId) values (?,?,?,?,?,?,?)", book.getBookName(),book.getPublish(),book.getPrice(),book.getAuthor(),book.getCount(),book.getBookPic(),book.getCategory().getCategoryId()); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 删除图书 * * @param bookId * @return */ @Override public int del(int bookId) { try { return qr.update("delete from book where bookId = ?",bookId); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 修改图书 * * @param book * @return */ @Override public int edit(Book book) { try { return qr.update("update book set bookName = ?,publish =?,price =? ,author =?,count = ?,bookPic = ?,categoryId =? where bookId = ? ", book.getBookName(), book.getPublish(), book.getPrice(), book.getAuthor(), book.getCount(), book.getBookPic(), book.getCategory().getCategoryId(), book.getBookId() ); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 查询所有图书 * * @return */ @Override public List<Book> getAllBooks() { try { return qr.query("select * from book",new BeanListHandler<Book>(Book.class)); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 根据分类查询图书 * * @param category * @return */ @Override public List<Book> getBookByCategory(Category category) { try { return qr.query("select * from book,category where book.categoryId = category.categoryId and categoryName = ? ", new BeanListHandler<Book>(Book.class),category.getCategoryName()); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 根据图书名称查询图书 * * @param bookName * @return */ @Override public List<Book> getBookByBookName(String bookName) { try { return qr.query("select * from book where bookName = ?",new BeanListHandler<Book>(Book.class),bookName); } catch (SQLException e) { throw new RuntimeException(e); } } /** * 根据图书编号查询图书 * * @param bookId * @return */ @Override public Book getBookById(int bookId) { try { return qr.query("select * from book where bookId = ?",new BeanHandler<Book>(Book.class),bookId); } catch (SQLException e) { throw new RuntimeException(e); } } }
难点来了?
- 图书添加页面的上传功能
- 图书添加页面的类目回显功能
添加图书页面 : addBook.jsp
<%-- Created by IntelliJ IDEA. User: Mryang Date: 2021/10/11 Time: 14:18 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--不要遗忘我咯,否则c标签无法使用啦--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>添加图书</title> </head> <body> <form action="/bookServlet?op=addBook" method="post"> 图书名称:<input type="text" name="bookName" id="bookName"> <br/> 图书作者:<input type="text" name="author" id="author"> <br/> 图书单价:<input type="text" name="price" id="price"> <br/> 图书出版社:<input type="text" name="publish" id="publish"> <br/> 图书库存:<input type="text" name="count" id="count"> <br/> 图书类目: <select> <c:forEach items="${list}" var="item"> <option value="${item.categoryName}">${item.categoryName}</option> </c:forEach> </select> <br/> 上传图片:<input type="file" name="bookPic" id="bookPic"> <br/> <input type="submit" value="添加类目"> </form> </body> </html>
初步编写BookServlet
package cn.javabs.web.servlet; import cn.javabs.entity.Category; import cn.javabs.service.CategoryService; import cn.javabs.service.impl.CategoryServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/bookServlet") public class BookServlet extends HttpServlet { CategoryService cs = new CategoryServiceImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 编码 */ request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String op = request.getParameter("op"); switch (op){ case "toAddBook": toAddBook(request,response); break; case "addBook" : addBook(request, response); break; case "delBook" : delBook(request, response); break; case "editBook" : editBook(request, response); break; case "updateBook" : updateBook(request, response); break; case "bookList" : bookList(request, response); break; default: System.out.println("前台传递的参数有误,请查正"); break; } } // 去添加图书页面的跳转 private void toAddBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Category> categoryList = cs.findAllCategory(); request.setAttribute("list",categoryList); request.getRequestDispatcher("addBook.jsp").forward(request,response); } private void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String bookName = request.getParameter("bookName"); String publish = request.getParameter("publish"); String sprice = request.getParameter("price");// 类型不对、需转化为Double double price = Double.parseDouble(sprice); String author = request.getParameter("author"); String scount = request.getParameter("count");// 类型不对、需转化为int int count = Integer.parseInt(scount); // String bookPic = request.getParameter("bookPic"); String categoryName = request.getParameter("categoryName"); //TODO 没写完,稍后继续 } private void delBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ } private void editBook(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { } private void updateBook(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { } private void bookList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ } }
提示页面进行‘改造’ message.jsp
<%-- Created by IntelliJ IDEA. User: Mryang Date: 2021/10/11 Time: 14:10 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <center> ${msg} <hr/> 还有 <span id="num" style="color: red"></span> 秒跳转 </center> </body> </html> <script> // 1 首先定义变量 var count = 6; var time = function() { // 声明时间递减方法 count = count - 1; if (count == 0){ //跳转到首页 window.location.href = "http://localhost:8080"; }else{ // 将倒计时的数字 输出到 页面内 document.getElementById("num").innerHTML = count; // 定时器 每1秒钟 执行递归调用自己一次 setTimeout(time,1000); } } time(); </script>
BookServlet 部分代码
package cn.javabs.web.servlet; import cn.javabs.entity.Book; import cn.javabs.entity.Category; import cn.javabs.service.BookService; import cn.javabs.service.CategoryService; import cn.javabs.service.impl.BookServiceImpl; import cn.javabs.service.impl.CategoryServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Random; @WebServlet("/bookServlet") @MultipartConfig public class BookServlet extends HttpServlet { CategoryService cs = new CategoryServiceImpl(); BookService bs = new BookServiceImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 编码 */ request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String op = request.getParameter("op"); switch (op){ case "toAddBook": toAddBook(request,response); break; case "addBook" : addBook(request, response); break; case "delBook" : delBook(request, response); break; case "editBook" : editBook(request, response); break; case "updateBook" : updateBook(request, response); break; case "bookList" : bookList(request, response); break; default: System.out.println("前台传递的参数有误,请查正"); break; } } // 去添加图书页面的跳转 private void toAddBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Category> categoryList = cs.findAllCategory(); request.setAttribute("list",categoryList); request.getRequestDispatcher("addBook.jsp").forward(request,response); } private void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String bookName = request.getParameter("bookName"); String publish = request.getParameter("publish"); String sprice = request.getParameter("price");// 类型不对、需转化为Double double price = Double.parseDouble(sprice); String author = request.getParameter("author"); String scount = request.getParameter("count");// 类型不对、需转化为int int count = Integer.parseInt(scount); String scategoryId = request.getParameter("categoryId"); int categoryId = Integer.parseInt(scategoryId); // 获取路径 String path = this.getServletConfig().getServletContext().getRealPath("/upload/"); System.out.println("path = " + path); // 获取文件 Part part = request.getPart("bookPic"); // 获取文件名称 String fileName = part.getSubmittedFileName(); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");// y 年 M 月 d 日 h 时 分 秒 String time = sdf.format(date); fileName = time + "_" + fileName ; System.out.println("新的文件名称 = " + fileName); File file = new File(path); if (!file.exists()){ // 创建文件的目录 file.mkdirs(); } // 上传文件 part.write(path + fileName); Category category = new Category(); category.setCategoryId(categoryId); Book book = new Book(bookName,publish,price,author,count,fileName,category); bs.addBook(book); } private void delBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ } private void editBook(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { } private void updateBook(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { } private void bookList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ } }
BookServlet 查询图书功能& 图书删除功能
/** * 删除图书 * @param request * @param response * @throws ServletException * @throws IOException */ private void delBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String sid = request.getParameter("id"); int id = Integer.parseInt(sid); int row = bs.delBook(id); if(row > 0){ request.setAttribute("msg","删除图书成功!"); request.getRequestDispatcher("message.jsp").forward(request,response); }else{ request.setAttribute("msg","删除图书失败!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } /** * 图书列表 查询所有图书 * @param request * @param response * @throws ServletException * @throws IOException */ private void bookList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ List<Book> bookList = bs.findAllBooks(); List<Book> bList = new ArrayList<>(); for (Book book : bookList) { System.out.println("book1 :" + book); Category category = cs.findCategoryById(book.getCategoryId()); book.setCategory(category); System.out.println("book2 :" + book); bList.add(book); } if (bList.size() > 0 && bList != null){ request.setAttribute("list",bList); request.getRequestDispatcher("bookList.jsp").forward(request,response); }else{ request.setAttribute("msg","尚未查询到图书!"); request.getRequestDispatcher("message.jsp").forward(request,response); } } ``` --- Jsp查询图书页面: bookList.jsp ```html <%-- Created by IntelliJ IDEA. User: Mryang Date: 2021/10/11 Time: 14:22 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--不要遗忘加入我,否则c标签无法使用--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>图书列表</title> </head> <style> .odd{ background-color: lightpink; } .even{ background-color: deepskyblue; } </style> <body> <table border="1" align="center" width="850px"> <tr> <th>编号</th> <th>图书名称</th> <th>出版社</th> <th>单价</th> <th>作者</th> <th>库存</th> <th>封面</th> <th>所属分类</th> <th>操作</th> </tr> <c:forEach items="${list}" var="item" varStatus="vs"> <tr class="${(vs.index + 1) % 2 == 0 ?'even':'odd'}"> <td>${item.bookId}</td> <td>${item.bookName}</td> <td>${item.publish}</td> <td>${item.price}</td> <td>${item.author}</td> <td>${item.count}</td> <td> <img src="/upload/${item.bookPic}" width="100px" > </td> <td>${item.category.categoryName}</td> <td> <a href="/bookServlet?op=editBook&id=${item.bookId}">修改</a> <a href="JavaScript:deleteBook('${item.bookId}')">删除</a> </td> </tr> </c:forEach> </table> </body> </html> <script> function deleteBook(id) { var sure = confirm("您确定要删除此项吗?") if (sure){ location.href = "/bookServlet?op=delBook&id=" + id; } } </script> ``` --- 小Bug修改: BookDaoImpl 修改查询语句 > 起初,查询语句是"select * from book" ,有错误,只能查询单表,需更改未双表查询 ```java /** * 查询所有图书 * * @return */ @Override public List<Book> getAllBooks() { try { List<Book> list = qr.query("select * from book , category where book.categoryId = category.categoryId", new BeanListHandler<Book>(Book.class)); System.out.println("list = " + list); return list; } catch (SQLException e) { throw new RuntimeException(e); } } ``` --- 实体类更改,加了一个变量为 categoryId, int类型,再给这个变量生成getter和setter方法,另重新生成toString方法即可 更改后代码如下: ```java package cn.javabs.entity; public class Book { private int bookId; private String bookName; private String publish;// 出版社 private double price; // 为什么不用float类型,因为默认就是double 、其次 使用float类型定义, 小数后需要添加f // 如float f1 = 6.5f private String author; private int count ; private String bookPic ; private Category category; private int categoryId; public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public Book(int bookId, String bookName, String publish, double price, String author, int count, String bookPic, Category category) { this.bookId = bookId; this.bookName = bookName; this.publish = publish; this.price = price; this.author = author; this.count = count; this.bookPic = bookPic; this.category = category; } public Book(String bookName, String publish, double price, String author, int count, String bookPic, Category category) { this.bookName = bookName; this.publish = publish; this.price = price; this.author = author; this.count = count; this.bookPic = bookPic; this.category = category; } public Book() { super(); } @Override public String toString() { return "Book{" + "bookId=" + bookId + ", bookName='" + bookName + '\'' + ", publish='" + publish + '\'' + ", price=" + price + ", author='" + author + '\'' + ", count=" + count + ", bookPic='" + bookPic + '\'' + ", category=" + category + ", categoryId=" + categoryId + '}'; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getPublish() { return publish; } public void setPublish(String publish) { this.publish = publish; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getBookPic() { return bookPic; } public void setBookPic(String bookPic) { this.bookPic = bookPic; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } } ```