• 暂时停更一段时间!
  • 近期网站将陆续进行前端页面改造!
  • 招募网站编辑,联系站长!

Javaweb基础案例之JSP+Servlet实现在线课程网站购物车

文章目录[隐藏]

技术点介绍

精华总结

巩固 jsp、Servlet、Filter 等技术点

学习如何设计并实现本地 JVM 缓存

在线学习网站购物车功能

1、课程列表显示

2、加入购物车、加入收藏

3、购物车列表显示及删除、计算

4、收藏列表显示及删除

应用到的技术点

JSP+JSTL

Servlet 及内部判断

LocalCache

Filter 解决数据传输乱码

项目结构初始化

项目预览

源码地址

开源地址

项目代码

com.geekerstar.cart.data.Cart

package com.geekerstar.cart.data;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/7/12 17:20
 * @Description:
 */
public class Cart {

    public Cart(Long id, Long productId, String name, int price, int count) {
        this.id = id;
        this.productId = productId;
        this.name = name;
        this.price = price;
        this.count = count;
        this.totalPrice = price * count;
    }

    private Long id;

    private Long productId;

    private String name;

    private int price;

    private int count;

    private int totalPrice;

    public void incrCount() {
        count++;
        this.totalPrice = price * count;
    }

    public boolean decrCount() {
        count--;
        this.totalPrice = price * count;
        if (0 == count) {
            return true;
        }
        return false;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getProductId() {
        return productId;
    }

    public void setProductId(Long productId) {
        this.productId = productId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(int totalPrice) {
        this.totalPrice = totalPrice;
    }
}

com.geekerstar.cart.data.LocalCache

package com.geekerstar.cart.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/7/12 16:24
 * @Description:
 */
public final class LocalCache {

    private static Map<Long, Product> productMap = new HashMap<>();

    private static Map<Long, Cart> cartMap = new HashMap<>();

    private static Map<Long, Product> favoriteMap = new HashMap<>();

    private static Map<Long, Product> browseLogMap = new HashMap<>();

    static {
        productMap.put(1l, new Product(1l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(2l, new Product(2l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(3l, new Product(3l, "JAVA", "JAVA 基础课程-基本语法", "介绍 java 基本语法特性及编写规范", "初级", 219));
        productMap.put(4l, new Product(4l, "JAVA", "JAVA 基础课程-JDBC", "介绍 JDBC 方式连接数据库", "初级", 219));
        productMap.put(5l, new Product(5l, "JAVA", "JAVA 基础课程—Socket", "介绍 Java 网络编程 Socket", "初级", 219));
        productMap.put(6l, new Product(6l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(7l, new Product(7l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(8l, new Product(8l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(9l, new Product(9l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(10l, new Product(10l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(11l, new Product(11l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(12l, new Product(12l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(13l, new Product(13l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(14l, new Product(14l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(15l, new Product(15l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(16l, new Product(16l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(17l, new Product(17l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(18l, new Product(18l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(19l, new Product(19l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(20l, new Product(20l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(21l, new Product(21l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(22l, new Product(22l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(23l, new Product(23l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(24l, new Product(24l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
        productMap.put(25l, new Product(25l, "HTML/CSS", "HTML+CSS 基础课程", "HTML+CSS 基础教程 8 小时带领大家步步深入学习标签用法和意义", "初级", 219));
    }

    private LocalCache() {
    }

    public static List<Product> getProducts() {
        return new ArrayList<>(productMap.values());
    }

    public static Product getProduct(Long id) {
        return productMap.get(id);
    }

    public static void addCart(Product product) {
        if (!cartMap.containsKey(product.getId())) {
            cartMap.put(product.getId(), new Cart(product.getId(), product.getId(), product.getName(), product.getPrice(), 1));
        } else {
            incrCart(product.getId());
        }
    }

    public static List<Cart> getCarts() {
        return new ArrayList<>(cartMap.values());
    }

    public static void delCart(Long productId) {
        cartMap.remove(productId);
    }

    public static void incrCart(Long productId) {
        cartMap.get(productId).incrCount();
    }

    public static void decrCart(Long productId) {
        boolean result = cartMap.get(productId).decrCount();
        if (result) {
            cartMap.remove(productId);
        }
    }

    public static Cart getCart(Long id) {
        return cartMap.get(id);
    }

    public static void addFavorite(Product product) {
        if (!favoriteMap.containsKey(product.getId())) {
            favoriteMap.put(product.getId(), product);
        }
    }

    public static void delFavorite(Long productId) {
        if (favoriteMap.containsKey(productId)) {
            favoriteMap.remove(productId);
        }
    }

    public static List<Product> getFavorites() {
        return new ArrayList<>(favoriteMap.values());
    }

    public static void addBrowseLog(Product product) {
        browseLogMap.put(product.getId(), product);
    }

    public static void deleteBrowseLog(Long productId) {
        browseLogMap.remove(productId);
    }

    public static List<Product> getBrowseLogs() {
        return new ArrayList<>(browseLogMap.values());
    }

    public static List<Product> getProducts(int page, int size, String name) {
        List<Product> products = new ArrayList<>();

        if (null != name && !"".equals(name)) {
            productMap.values().forEach(product -> {
                if (product.getName().contains(name)) {
                    products.add(product);
                }
            });
        } else {
            products.addAll(productMap.values());
        }

        int start = (page - 1) * size;
        int end = products.size() >= page * size ? page * size : products.size();
        return products.subList(start, end);
    }

    public static int getProductsCount(String name) {
        List<Product> products = new ArrayList<>();

        if (null != name && !"".equals(name)) {
            productMap.values().forEach(product -> {
                if (product.getName().contains(name)) {
                    products.add(product);
                }
            });
        } else {
            products.addAll(productMap.values());
        }
        return products.size();
    }

}

com.geekerstar.cart.data.Product

package com.geekerstar.cart.data;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/7/12 16:24
 * @Description:商品(课程)
 */
public class Product {

    public Product(long id, String tag, String name, String desc, String level, int price) {
        this.id = id;
        this.tag = tag;
        this.name = name;
        this.desc = desc;
        this.level = level;
        this.price = price;
    }

    private long id;
    //标签
    private String tag;
    //名称
    private String name;
    //描述
    private String desc;
    //级别
    private String level;
    //价格
    private int price;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

com.geekerstar.cart.filter.CharsetEncodingFilter

package com.geekerstar.cart.filter;

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 java.io.IOException;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/7/12 16:12
 * @Description:字符编码过滤器
 */
public class CharsetEncodingFilter implements Filter {

    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding(encoding);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}

com.geekerstar.cart.servlet.BrowseServlet

package com.geekerstar.cart.servlet;

import com.geekerstar.cart.data.LocalCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 浏览记录 Servlet
 *
 * @version 1.0
 */
public class BrowseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (Objects.equals(request.getServletPath(), "/browse/list.do")) {
            //从 Cookie 中取出全部,根据 ID 在 LocalCache 中查询出对应的全部 Product
            //将 Product 全部放入 List 中,并写入 request
            request.setAttribute("products", LocalCache.getBrowseLogs());
            request.getRequestDispatcher("/WEB-INF/views/biz/browse_list.jsp").forward(request, response);
        } else if (Objects.equals(request.getServletPath(), "/browse/delete.do")) {
            //从 request 中取出 cookie(按 cookie 的 name 匹配)
            //从 value 字符串中删除相应的 ID,把剩余的数据重新放入 cookie
//            for (Cookie cookie : request.getCookies()) {
//                if (Objects.equals("productIds", cookie.getName())) {
//                    //do
//                    break;
//                }
//            }
            String productId = request.getParameter("productId");
            if (null != productId) {
                LocalCache.deleteBrowseLog(Long.valueOf(productId));
            }
            response.sendRedirect("/browse/list.do");
        }
    }
}

com.geekerstar.cart.servlet.CartServlet

package com.geekerstar.cart.servlet;

import com.geekerstar.cart.data.Cart;
import com.geekerstar.cart.data.LocalCache;
import com.geekerstar.cart.data.Product;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * TODO {file desc}
 *
 * @version 1.0
 */
public class CartServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (Objects.equals("/cart/cart.do", req.getServletPath())) {
            String productId = req.getParameter("productId");
            if (null != productId) {
                Product product = LocalCache.getProduct(Long.valueOf(productId));
                LocalCache.addCart(product);
            }
            resp.sendRedirect("/cart/list.do");
        } else if (Objects.equals("/cart/delete.do", req.getServletPath())) {
            String productId = req.getParameter("productId");
            if (null != productId) {
                LocalCache.delCart(Long.valueOf(productId));
            }
            resp.sendRedirect("/cart/list.do");
        } else if (Objects.equals("/cart/incr.do", req.getServletPath())) {
            String productId = req.getParameter("productId");
            if (null != productId) {
                LocalCache.incrCart(Long.valueOf(productId));
            }
            resp.sendRedirect("/cart/list.do");
        } else if (Objects.equals("/cart/decr.do", req.getServletPath())) {
            String productId = req.getParameter("productId");
            if (null != productId) {
                LocalCache.decrCart(Long.valueOf(productId));
            }
            resp.sendRedirect("/cart/list.do");
        } else if (Objects.equals("/cart/settlement.do", req.getServletPath())) {
            String[] cartIds = req.getParameterValues("carts");
            int totalPrice = 0;
            for (int i = 0; i < cartIds.length; i++) {
                Cart cart = LocalCache.getCart(Long.valueOf(cartIds[i]));
                totalPrice += cart.getTotalPrice();
                LocalCache.delCart(cart.getId());
            }
            req.setAttribute("totalPrice", totalPrice);
            req.getRequestDispatcher("/WEB-INF/views/biz/settlement.jsp").forward(req, resp);
        } else if (Objects.equals("/cart/list.do", req.getServletPath())) {
            req.setAttribute("carts", LocalCache.getCarts());
            req.getRequestDispatcher("/WEB-INF/views/biz/cart.jsp").forward(req, resp);
        }
    }
}

com.geekerstar.cart.servlet.DetailInfoServlet

package com.geekerstar.cart.servlet;

import com.geekerstar.cart.data.LocalCache;
import com.geekerstar.cart.data.Product;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 详情 Servlet
 *
 * @version 1.0
 */
public class DetailInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (Objects.equals(request.getServletPath(), "/detail/detail.do")) {
            String productId = request.getParameter("productId");
            if (null != productId) {
//                Cookie existCookie = null;
//                for (Cookie cookie : request.getCookies()) {
//                    if (Objects.equals("productIds", cookie.getName())) {
//                        existCookie = cookie;
//                        break;
//                    }
//                }
//                if (null == existCookie) {
//                    existCookie  = new Cookie("productIds", "/");
//                }
//                existCookie.setValue(existCookie.getValue() + "," + productId);
//                response.addCookie(cookie);
                //判断 Cookie 是否存在,若存在则使用已有的,并读出原有数据
                //若不存在,则新建
                Product product = LocalCache.getProduct(Long.valueOf(productId));
                request.setAttribute("product", product);
                LocalCache.addBrowseLog(product);
            }
        }
        request.getRequestDispatcher("/WEB-INF/views/biz/detail.jsp").forward(request, response);
    }
}

com.geekerstar.cart.servlet.FavoriteServlet

package com.geekerstar.cart.servlet;

import com.geekerstar.cart.data.LocalCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 收藏控制器
 *
 * @version 1.0
 */
public class FavoriteServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (Objects.equals(req.getServletPath(), "/favorite/favorite.do")) {
            String productId = req.getParameter("productId");
            if (null != productId) {
                LocalCache.addFavorite(LocalCache.getProduct(Long.valueOf(productId)));
            }
            resp.sendRedirect("/favorite/list.do");
        } else if (Objects.equals(req.getServletPath(), "/favorite/delete.do")) {
            String productId = req.getParameter("productId");
            if (null != productId) {
                LocalCache.delFavorite(Long.valueOf(productId));
            }
            resp.sendRedirect("/favorite/list.do");
        } else if (Objects.equals(req.getServletPath(), "/favorite/list.do")) {
            req.setAttribute("products", LocalCache.getFavorites());
            req.getRequestDispatcher("/WEB-INF/views/biz/favorite.jsp").forward(req, resp);
        }
    }
}

com.geekerstar.cart.servlet.ProductServlet

package com.geekerstar.cart.servlet;

import com.geekerstar.cart.data.LocalCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Geekerstar(jikewenku.com)
 * @Date: 2018/7/12 16:19
 * @Description:商品(课程)控制器
 */
public class ProductServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setAttribute("products", LocalCache.getProducts());
//        req.getRequestDispatcher("/WEB-INF/views/biz/list.jsp").forward(req, resp);

        String name = req.getParameter("title");

        String pageStr = req.getParameter("page");
        int page = 1;
        if (null != pageStr && !"".equals(pageStr)) {
            page = Integer.parseInt(pageStr);
        }

        int totalProducts = LocalCache.getProductsCount(name);
        int totalPage = totalProducts % 12 > 0 ? totalProducts / 12 + 1 : totalProducts / 12;

        req.setAttribute("curPage", page);
        req.setAttribute("prePage", page > 1 ? page - 1 : 1);
        req.setAttribute("nextPage", totalPage > page ? page + 1 : totalPage);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("title", name);


        req.setAttribute("products", LocalCache.getProducts(page, 12, name));
        req.getRequestDispatcher("/WEB-INF/views/biz/list.jsp").forward(req, resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}

丨极客文库, 版权所有丨如未注明 , 均为原创丨
本网站采用知识共享署名-非商业性使用-相同方式共享 3.0 中国大陆许可协议进行授权
转载请注明原文链接:Javaweb 基础案例之 JSP+Servlet 实现在线课程网站购物车
喜欢 (0)
[247507792@qq.com]
分享 (0)
极客文库
关于作者:
一只程序猿

邀请您免费 注册账号 登录 即可参与讨论!

(2)个小伙伴在吐槽
  1. 学长,注释太少,看着懵懵的,好多看不懂QWQ
    silrntrr2018-08-18 21:57 Windows 10 | Chrome 65.0.3325.181
    • 极客文库
      这个项目,可以clone下源码自己机器上跑一下。现在企业开发基本不会用jsp了,一般是前后端分离,主要了解一下servlet就行了,重心放在后端业务逻辑的处理上。
      Geekerstar2018-08-19 23:00 Windows 10 | Firefox浏览器 61.0