《尚硅谷》JavaWeb课程书城项目笔记——第五阶段(1):图书模块

目录

1、编写图书模块数据表

2、编写图书模块的JavaBean

3、编写图书模块的Dao、DaoImpl、DaoTest

4、编写图书模块的Service、ServiceImpl、ServiceTest

5、编写图书模块的Web层,进行页面调试


1、编写图书模块数据表

创建数据表

为数据表添加数据

 注:创建与操作表的执行语句见附件:sql.sql

2、编写图书模块的JavaBean

package pojo;

import java.math.BigDecimal;

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";

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", sales=" + sales +
                ", stock=" + stock +
                ", imgPath='" + imgPath + '\'' +
                '}';
    }

    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 Book() {

    }

    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;
        }
    }
}

3、编写图书模块的Dao、DaoImpl、DaoTest

BookDao

package dao;

import pojo.Book;

import java.util.List;

public interface BookDao {

    public int addBook(Book book);

    public int deleteBookById(Integer id);

    public int updateBook(Book book);

    public Book queryBookById(Integer id);

    public List<Book> queryBooks();
}

BookDaoImpl 

package dao.impl;

import dao.BookDao;
import pojo.Book;

import java.util.List;

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);
    }
}

BookDaoTest

package test;

import dao.BookDao;
import dao.impl.BookDaoImpl;
import org.junit.Test;
import pojo.Book;

import java.math.BigDecimal;

import static org.junit.Assert.*;

public class BookDaoTest {

    private BookDao bookDao = new BookDaoImpl();

    @Test
    public void addBook() {
        bookDao.addBook(new Book(null,"一念永恒","白小白",new BigDecimal(99),1000,859,null));
    }

    @Test
    public void deleteBookById() {
        bookDao.deleteBookById(21);
    }

    @Test
    public void updateBook() {
        bookDao.updateBook(new Book(21,"成仙","白小白",new BigDecimal(999),1000,0,null));
    }

    @Test
    public void queryBookById() {
        System.out.println(bookDao.queryBookById(21));
    }

    @Test
    public void queryBooks() {
        for (Book bookList:bookDao.queryBooks()) {
            System.out.println(bookList);
        }
    }
}

4、编写图书模块的Service、ServiceImpl、ServiceTest

编写BookService

package service;

import pojo.Book;

import java.util.List;

public interface BookService {

    public void addBook(Book book);

    public void deleteBookById(Integer id);

    public void updateBook(Book book);

    public Book queryBookById(Integer id);

    public List<Book> queryBooks();
}

编写BookServiceImpl

package service.impl;

import dao.BookDao;
import dao.impl.BookDaoImpl;
import pojo.Book;
import service.BookService;

import java.util.List;

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();
    }
}

编写BookServiceTest

package test;

import org.junit.Test;
import pojo.Book;
import service.BookService;
import service.impl.BookServiceImpl;

import java.math.BigDecimal;

import static org.junit.Assert.*;

public class BookServiceTest {

    private BookService bookService = new BookServiceImpl();

    @Test
    public void addBook() {
        bookService.addBook(new Book(null,"大话Java","Tom",new BigDecimal(99),7000,8000,null));
    }

    @Test
    public void deleteBookById() {
        bookService.deleteBookById(22);
    }

    @Test
    public void updateBook() {
        bookService.updateBook(new Book(22,"大话Java","Jerry",new BigDecimal(909),700,800,null));
    }

    @Test
    public void queryBookById() {
        System.out.println(bookService.queryBookById(22));
    }

    @Test
    public void queryBooks() {
        for (Book bookList : bookService.queryBooks()) {
            System.out.println(bookList);
        }
    }
}

5、编写图书模块的Web层,进行页面调试

图书列表功能的实现

  • 新建BookServlet方法并在web.xml中进行配置
<servlet>
        <servlet-name>BookServlet</servlet-name>
        <servlet-class>web.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>BookServlet</servlet-name>
        <url-pattern>/manager/bookServlet</url-pattern>
</servlet-mapping>
  • 在BookServlet中添加list方法
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1 查询所有图书
        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);

    }
  • 修改图书管理的请求地址
<div>
    <a href="manager/bookServlet?action=list">图书管理</a>
    <a href="order_manager.jsp">订单管理</a>
    <a href="../../index.jsp">返回商城</a>
</div>
  • 修改图书菜单页面显示数据(先导入jsp的jar包)

<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="pages/manager/book_edit.jsp">添加图书</a></td>
			</tr>	
		</table>
	</div>

5.2、图书添加功能的实现

  • 在BookServlet中添加add方法
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1 获取请求的参数==封装成为 Book 对象
        Book book = WebUtils.copyParamToBean(req.getParameterMap(),new Book());
        // 2 调用 BookService.addBook()保存图书
        bookService.addBook(book);
        // 3 跳到图书列表页面
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
    }

注:此处页面跳转采用重定向方式,避免表单重复提交。 

  • 修改显示页面(book_edit.jsp)
<div id="main">
	<form action="manager/bookServlet">
		<input type="hidden" name="action" value="add">
		<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="时间简史"/></td>
				<td><input name="price" type="text" value="30.00"/></td>
				<td><input name="author" type="text" value="霍金"/></td>
				<td><input name="sales" type="text" value="200"/></td>
				<td><input name="stock" type="text" value="300"/></td>
				<td><input type="submit" value="提交"/></td>
			</tr>	
		</table>
	</form>
</div>

5.3、图书删除功能的实现

  • 在webUtils中封装将字符串类型转换成整形输出的功能
/**
     * 将字符串类型转换成整形输出
     * @param strInt
     * @param defaultValue
     * @return
     */
    public static int parseInt(String strInt,int defaultValue) {
        try {
            return Integer.parseInt(strInt);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return 0;
    }
  • 在BookServlet中添加delete方法

protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 获取请求的参数——需要删除的图书id
        int id = WebUtils.parseInt(req.getParameter("id"), 0);

        // 2 使用bookService执行删除操作
        bookService.deleteBookById(id);

        // 3 页面重定向回图书列表管理页面(/manager/bookServlet?action=list)
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
    }
  • 给删除操作增减提示
<script type="text/javascript">
		$(function () {
			$("a.deleteClass").click(function () {
				return confirm("你确定要删除【" + $(this).parent().parent().find("td:first").text() + "】?")
            });
        });
</script>

图书修改功能的实现

  • 在BookServlet中添加getBook方法

    protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 获取请求的参数
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        // 2 执行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);
    }
  • 在图书管理页面修改提交地址

<td><a href="manager/bookServlet?action=getBook&id=${book.id}">修改</a></td>
  • 在book_edit.jsp中修改要显示的数据

<div id="main">
			<form action="manager/bookServlet">
				<input type="hidden" name="action" value="add">
				<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>
  • 在BookServlet中添加update方法
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1 获取请求的参数并封装成对象
        Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
        // 2 执行bookService.updateBook操作修改数据
        bookService.updateBook(book);
        // 3 请求重定向到/manager/bookServlet?action=list
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=list");
}
  • 解决 book_edit.jsp 页面,即要实现添加,又要实现修改操作
<input type="hidden" name="action" value="${empty requestScope.book?'add':'update'}">
<input type="hidden" name="id" value="${requestScope.book.id}">

 

注:本文章所含内容来源于尚硅谷教育,仅供学习参考使用。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值