(四)加入购物车和购物车操作

ShoppingCart.java

package com.aff.bookstore.domain;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ShoppingCart {
    
    private Map<Integer, ShoppingCartItem> books = new HashMap<>();
    
    /**
     * 修改指定购物项的数量
     */
    public void updateItemQuantity(Integer id, int quantity){
        ShoppingCartItem sci =books.get(id);
        if(sci != null){
            sci.setQuantity(quantity);
        }
    }
    
    /**
     * 移除指定的购物项
     * @param id
     */
    public void removeItem(Integer id){
        books.remove(id);
    }
    
    /**
     * 清空购物车
     */
    public void clear(){
        books.clear();
    }
    
    /**
     * 返回购物车是否为空
     * @return
     */
    public boolean isEmpty(){
        return books.isEmpty();
    }
    
    /**
     * 获取购物车中所有的商品的总的钱数
     * @return
     */
    public float getTotalMoney(){
        float total = 0;
        
        for(ShoppingCartItem sci: getItems()){
            total += sci.getItemMoney();
        }
        
        return total;
    }
    
    /**
     * 获取购物车中的所有的 ShoppingCartItem 组成的集合
     * @return
     */
    public Collection<ShoppingCartItem> getItems(){
        return books.values();
    }
    
    /**
     * 返回购物车中商品的总数量
     * @return
     */
    public int getBookNumber(){
        int total = 0;
        
        for(ShoppingCartItem sci: books.values()){
            total += sci.getQuantity();
        }
        
        return total;
    }
    
    public Map<Integer, ShoppingCartItem> getBooks() {
        return books;
    }
    
    /**
     * 检验购物车中是否有 id 指定的商品        
     * @param id
     * @return
     */
    public boolean hasBook(Integer id){
        return books.containsKey(id);
    }        
            
    /**
     * 向购物车中添加一件商品        
     * @param book
     */
    public void addBook(Book book){
        //1. 检查购物车中有没有该商品, 若有, 则使其数量 +1, 若没有, 
        //新创建其对应的 ShoppingCartItem, 并把其加入到 books 中
        ShoppingCartItem sci = books.get(book.getId());
        
        if(sci == null){
            sci = new ShoppingCartItem(book);
            books.put(book.getId(), sci);
        }else{
            sci.increment();
        }
    }
}

ShoppingCartItem.java

package com.aff.bookstore.domain;

/**
 * 封装了购物车中的商品, 包含对商品的引用以及购物车中该商品的数量
 *
 */
public class ShoppingCartItem {

    private Book book;
    private int quantity;
    
    public ShoppingCartItem(Book book) {
        this.book = book;
        this.quantity = 1;
    }
    
    public Book getBook() {
        return book;
    }
    
    public int getQuantity() {
        return quantity;
    }
    
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    
    /**
     * 返回该商品在购物车中的钱数
     * @return
     */
    public float getItemMoney(){
        return book.getPrice() * quantity;
    }
    
    /**
     * 使商品数量 + 1
     */
    public void increment(){
        quantity++;
    }
    
    
}

BookStoreWebUtils.java

package com.aff.bookstore.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.aff.bookstore.domain.ShoppingCart;

//从session中获取购物车对象,若session中没有,则创建一个新的购物车对象放入到session中, 若有则直接返回
public class BookStoreWebUtils {
    public static ShoppingCart getShopingCart(HttpServletRequest request) {
        HttpSession session = request.getSession();

        ShoppingCart sc = (ShoppingCart) session.getAttribute("ShoppingCart");
        if (sc==null    ) {
            sc = new  ShoppingCart();
            session.setAttribute("ShoppingCart", sc);
        }
        return sc;
    }
}

cart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@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">
<title>Insert title here</title>
<script type="text/javascript" src="script/jquery-1.12.3.js"></script>
<%@include file="/commons/queryCondition.jsp" %>
<script type="text/javascript">
$(function(){
    $(".delete").click(function(){
        var tr = $(this).parent().parent();
        var title =$.trim($tr.find("td:first").text());
        var flag = confirm("确定要删除"+title+"的信息吗"");
        
        if (flag) {
            return true;
        }
        
        return false;
        
    });
});

</script>
</head>
<body>
            <center>
                        <br><br>
                        <div>您的购物差中共有 ${sessionScope.ShoppingCart.bookNumber} 本书</div>
                        <table cellpadding="10">
                                <tr>
                                        <td>Title</td>
                                        <td>Quantity</td>
                                        <td>Price</td>
                                        <td>&nbsp;</td>
                                </tr>
                                <c:forEach items="${sessionScope.ShoppingCart.items }" var="item">
                                <tr>
                                        <td>${item.book.title }</td>
                                        <td>${item.quantity }</td>
                                        <td>${item.book.price }</td>
                                        <td><a href="bookServlet?method=remove&pageNo=${param.pageNo }&id=${item.book.id}" class="delete">删除</a></td>
                                </tr>
                                </c:forEach>
                                
                                <tr>
                                    <td colspan="4"> 总金额:¥${sessionScope.ShoppingCart.totalMoney}</td>
                                </tr>
                                
                                <tr>
                                        <td colspan="4">
                                                             <a href="bookServlet?method=getBooks&pageNo=${param.pageNo }">继续购物</a>
                                                            &nbsp;&nbsp;
                                                             <a href="bookServlet?method=clear" >清空购物车</a>
                                                            &nbsp;&nbsp;
                                                             <a href="">结账</a>
                                                            &nbsp;&nbsp;
                                        </td>
                                </tr>
                        
                        </table>
            
            </center>
            <br><br>

</body>
</html>

empty.jsp

<body>
    <h3>您的购物车为空</h3>
    <a href="index.jsp">继续购物</a>
</body>

BookServlet.java

package com.aff.bookstore.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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 com.aff.bookstore.domain.Book;
import com.aff.bookstore.domain.ShoppingCart;
import com.aff.bookstore.service.BookService;
import com.aff.bookstore.web.BookStoreWebUtils;
import com.aff.bookstore.web.CriteriaBook;
import com.aff.bookstore.web.Page;

@WebServlet("/bookServlet")
public class BookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    private BookService bookService = new BookService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String methodName = request.getParameter("method");
        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
                    HttpServletResponse.class);
            method.setAccessible(true);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void clear(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ShoppingCart sc = BookStoreWebUtils.getShopingCart(request);
        bookService.clearShoppingCart(sc);
        request.getRequestDispatcher("/WEB-INF/pages/empty.jsp").forward(request, response);
    }

    // 删除商品
    protected void remove(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        int id = -1;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
        }
        ShoppingCart sc = BookStoreWebUtils.getShopingCart(request);
        bookService.removeItemFromShoppingCart(sc, id);
        if (sc.isEmpty()) {
            request.getRequestDispatcher("/WEB-INF/pages/empty.jsp").forward(request, response);
        }

        // 删除完再转发为回来
        request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response);

    }

    protected void toCartPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response);
    }

    protected void addToCart(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1.获取商品的id
        String idStr = request.getParameter("id");
        int id = -1;
        boolean flag = false;

        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
        }

        if (id > 0) {
            // 2.获取购物差对象
            ShoppingCart sc = BookStoreWebUtils.getShopingCart(request);

            // 3.调用 BookService 的addToCart() 方法 把商品放到购物车中
            flag = bookService.addToCart(id, sc);
        }

        if (flag) {
            // 4.直接调用 getBooks()方法
            getBooks(request, response);
            return;
        }
        response.sendRedirect(request.getContextPath() + "/errror-1.jsp");
    }

    protected void getBook(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        int id = -1;
        Book book = null;

        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
        }

        if (id > 0) {
            book = bookService.getBook(id);
            if (book == null) {
                response.sendRedirect(request.getContextPath() + "/errror-1.jsp");
                return;
            }
        }
        request.setAttribute("book", book);
        request.getRequestDispatcher("/WEB-INF/pages/book.jsp").forward(request, response);
    }

    protected void getBooks(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pageNoStr = request.getParameter("pageNo");
        String minPriceStr = request.getParameter("minPrice");
        String maxPriceStr = request.getParameter("maxPrice");

        int pageNo = 1;
        int minPrice = 0;
        int maxPrice = Integer.MAX_VALUE;
        try {
            pageNo = Integer.parseInt(pageNoStr);
        } catch (Exception e) {
        }
        try {
            minPrice = Integer.parseInt(minPriceStr);
        } catch (Exception e) {
        }
        try {
            maxPrice = Integer.parseInt(maxPriceStr);
        } catch (Exception e) {
        }
        CriteriaBook criteriaBook = new CriteriaBook(minPrice, maxPrice, pageNo);
        Page<Book> page = bookService.getPage(criteriaBook);

        request.setAttribute("bookpage", page);
        request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response);

    }

}

解决中文乱码问题 

EncodingFilter.java

package com.aff.bookstore.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("/*")
public class EncodingFilter implements Filter {

    public EncodingFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String encoding = filterConfig.getServletContext().getInitParameter("encoding");
        request.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }

    private FilterConfig filterConfig = null;

    public void init(FilterConfig fConfig) throws ServletException {
        this.filterConfig = fConfig;
    }

}

web.xml

<context-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</context-param>

目录

猜你喜欢

转载自www.cnblogs.com/afangfang/p/12912530.html