最新公告
  • 欢迎您光临极客文库,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入我们
  • 技术点介绍

    精华总结

    巩固jsp、Servlet、Filter等技术点

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

    在线学习网站购物车功能

    1、课程列表显示

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

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

    4、收藏列表显示及删除

    应用到的技术点

    JSP+JSTL

    Servlet及内部判断

    LocalCache

    Filter解决数据传输乱码

    项目结构初始化

    项目预览

    源码地址

    [gt href=’https://github.com/geekerstar/JSP-Servlet-CartDemo’]开源地址[/gt]

    项目代码

    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 productMap = new HashMap<>();
    
        private static Map cartMap = new HashMap<>();
    
        private static Map favoriteMap = new HashMap<>();
    
        private static Map 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 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 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 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 getBrowseLogs() {
            return new ArrayList<>(browseLogMap.values());
        }
    
        public static List getProducts(int page, int size, String name) {
            List 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 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();
        }
    }
    
    本站所有文章均由网友分享,仅用于参考学习用,请勿直接转载,如有侵权,请联系网站客服删除相关文章。若由于商用引起版权纠纷,一切责任均由使用者承担
    极客文库 » Javaweb基础案例之JSP+Servlet实现在线课程网站购物车

    常见问题FAQ

    如果资源链接失效了怎么办?
    本站用户分享的所有资源都有自动备份机制,如果资源链接失效,请联系本站客服QQ:2580505920更新资源地址。
    如果用户分享的资源与描述不符怎么办?
    可以联系客服QQ:2580505920,如果要求合理可以安排退款或者退赞助积分。
    如何分享个人资源获取赞助积分或其他奖励?
    本站用户可以分享自己的资源,但是必须保证资源没有侵权行为。点击个人中心,根据操作填写并上传即可。资源所获收益完全归属上传者,每周可申请提现一次。
    如果您发现了本资源有侵权行为怎么办?
    及时联系客服QQ:2580505920,核实予以删除。

    3 评论

    1. 学长,请问一下这个BrowseServlet文件中”/browse/list.do”这个部分是什么意思?这个看不懂,每次运行都是这个找不到

    2. 学长,注释太少,看着懵懵的,好多看不懂QWQ

      1. 这个项目,可以clone下源码自己机器上跑一下。现在企业开发基本不会用jsp了,一般是前后端分离,主要了解一下servlet就行了,重心放在后端业务逻辑的处理上。

    Leave a Reply

    Hi, 如果你对这款资源有疑问,可以跟我联系哦!

    联系发布者

    3 评论

    1. 学长,请问一下这个BrowseServlet文件中”/browse/list.do”这个部分是什么意思?这个看不懂,每次运行都是这个找不到

    2. 学长,注释太少,看着懵懵的,好多看不懂QWQ

      1. 这个项目,可以clone下源码自己机器上跑一下。现在企业开发基本不会用jsp了,一般是前后端分离,主要了解一下servlet就行了,重心放在后端业务逻辑的处理上。

    Leave a Reply

    Hi, 如果你对这款资源有疑问,可以跟我联系哦!

    联系发布者
    • 108会员总数(位)
    • 3695资源总数(个)
    • 3本周发布(个)
    • 0 今日发布(个)
    • 181稳定运行(天)

    欢迎加入「极客文库」,成为原创作者从这里开始!

    立即加入 了解更多
    成为赞助用户享有更多特权立即升级