zoukankan      html  css  js  c++  java
  • 购物车模块

    学习开发购物车模块

    发现一个问题,如果web.xml中配置映射路径中/servlet/***,在serlet中,跳转的时候,会在路径中自动添加/servlet,这个真是非常的恶心。下次设置映射的时候,不加/servlet.

    首先给出购买页。这里用静态页面。

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'shoMerchandise.jsp' starting page</title>
    
    </head>
    
    <body>
        <table width=424 " height="583" border="0" align="center">
            <tr>
                <td width="190"><img alt="hpcomputer"
                    src="images/hppavilion.jpg"></td>
                <td width="224"><img src="images/lenovo.jpg">
                <td>
            </tr>
            <tr>
                <td>笔记本电脑</td>
                <td>移动硬盘
            </tr>
            <tr>
                <td>价格:5999.99元</td>
                <td>价格:688.88</td>
            </tr>
            <tr>
                <td>
                <a href="servlet/AddShoppingCart?id=0001&name=笔记本电脑&price=5999.00"><img src="images/buybutton.gif" width="71" height="21" border="0" /></a>
                </td>
                <td>
                <a href="servlet/AddShoppingCart?id=0002&name=移动硬盘&price=688.88"><img src="images/buybutton.gif" width="71" height="21" border="0"/></a>
            </tr>
        </table>
    </body>
    </html>
    View Code

    点击购买,跳转到addShoppingCart.java,这是一个servlet,处理的事件为把点击购买的商品添加到购物车中:

    过程是,首先从session中读取shoppingcart,如果为空,则一个购物车类(通过Shop类),然后在session中新建一个购物车的信息。

    session.setAttribute("shoppingcart", cart);

    否则的话,就从session中读取出shoppingcart的信息。保存在javabean:ShoppingCart new cart中。

    然后接收request传递到服务器的信息,并验证信息的合法性。

    //获得商品的基本信息
            String id=request.getParameter("id");
            String name=request.getParameter("name");
            byte source [] = name.getBytes("iso8859-1");
             name = new String (source,"UTF-8");
            String quantity=request.getParameter("q");
            String price = request.getParameter("price");
            System.out.println(id+name+quantity+price);
            
            //检验要加入的商品信息
            if(StringTool.validateNull(id)||StringTool.validateNull("name")||StringTool.validateNull("price")||StringTool.validateNull("quantity")){
                printError(request,response);
                return;
            }
            id=StringTool.filterHtml(id);
            name=StringTool.filterHtml(name);
    View Code

    之后,执行cart的添加商品javebean:CartItem的addItem方法,把商品添加到cart中去。

            try{
                if(StringTool.validateNull(quantity)){
                    //根据传入的商品数据创建商品,然后利用addCartItem方法添加进购物车
                    cart.addItem(new CartItem(id,name,1,Double.parseDouble(price)));
                    System.out.println(Double.parseDouble(price));
                }else{
                    cart.addItem(new CartItem(id,name,Integer.parseInt(quantity),Double.parseDouble(price)));
                }
            }catch(NumberFormatException e){
                printError(request,response);
                return;
            }
    View Code

    这里并没有更新session,我这样理解:cart是建立的一个指针,它们之间(cart、session)是浅复制,所以不必更新session。

    跳转到展示购物车的页面。

    response.sendRedirect("GetShoppingCart");

    这里就是我说的自动添加/servlet那个问题之一,按理说,按照映射的话,应该是/servlet/×××,但是由于是在servlet中跳转的,所以会自动在跳转路径中添加/servlet。

    可以自己试一下。

    如果商品添加失败,在输出错误信息。

    下面是完整代码:AddShoppingCart.java

    package com.cjg.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.cjg.bean.CartItem;
    import com.cjg.bean.ShoppingCart;
    import com.cjg.tools.*;
    
    public class AddShoppingCart extends HttpServlet {
    
        /**
             * The doGet method of the servlet. <br>
             *
             * This method is called when a form has its tag value method equals to get.
             * 
             * @param request the request send by the client to the server
             * @param response the response send by the server to the client
             * @throws ServletException if an error occurred
             * @throws IOException if an error occurred
             */
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            doPost(request,response);
        }        
        /**
             * The doPost method of the servlet. <br>
             *
             * This method is called when a form has its tag value method equals to post.
             * 
             * @param request the request send by the client to the server
             * @param response the response send by the server to the client
             * @throws ServletException if an error occurred
             * @throws IOException if an error occurred
             */
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            response.setContentType("text/html");
              response.setCharacterEncoding("utf-8");
              
            PrintWriter out = response.getWriter();
            response.setContentType("text/html;charset:utf-8");
            HttpSession session = request.getSession();//获取session
            ShoppingCart cart=(ShoppingCart) session.getAttribute("shoppingcart");
            //当购物车为空时
            if(cart==null){
                cart=new ShoppingCart();
                session.setAttribute("shoppingcart", cart);
                
            }
            
            //获得商品的基本信息
            String id=request.getParameter("id");
            String name=request.getParameter("name");
            byte source [] = name.getBytes("iso8859-1");
             name = new String (source,"UTF-8");
            String quantity=request.getParameter("q");
            String price = request.getParameter("price");
            System.out.println(id+name+quantity+price);
            
            //检验要加入的商品信息
            if(StringTool.validateNull(id)||StringTool.validateNull("name")||StringTool.validateNull("price")||StringTool.validateNull("quantity")){
                printError(request,response);
                return;
            }
            id=StringTool.filterHtml(id);
            name=StringTool.filterHtml(name);
            try{
                if(StringTool.validateNull(quantity)){
                    //根据传入的商品数据创建商品,然后利用addCartItem方法添加进购物车
                    cart.addItem(new CartItem(id,name,1,Double.parseDouble(price)));
                    System.out.println(Double.parseDouble(price));
                }else{
                    cart.addItem(new CartItem(id,name,Integer.parseInt(quantity),Double.parseDouble(price)));
                }
            }catch(NumberFormatException e){
                printError(request,response);
                return;
            }
            response.sendRedirect("GetShoppingCart");
            //System.out.println("ssss");
        }
        
        //商品添加失败的输出信息
        private void printError(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
            
            response.setContentType("text/html;charset:utf-8");
            PrintWriter out =response.getWriter();
            out.println("<html>");
            out.println("<head><title>购买商品失败</title></head>");
            out.println("<body>");
            out.println("<h1>缺少商品参数或者商品参数不正确,添加商品到购物车中不成功</h1><br><br>");
            out.println("<a href="/onlineshoppingcart/showMerchandise.htm">继续浏览商品,添加商品到购物车</a><br>");
            out.println("</body>");
            out.println("</html>");
            out.flush();
            out.close();
        }
    
    }
    View Code

     解决form表单提交乱码的问题:

    byte source [] = name.getBytes("iso8859-1"); 
    name = new String (source,"UTF-8");

    先把提交的内容以iso编码格式存储,然后保存为utf-8格式。

    然后是商品展示页:

    用servlet小程序处理,显示购物车的全部商品:

    首先取得session

    HttpSession session =request.getSession();

    然后判断是否有shoppingcart记录,如果没有,显示购物车为空,如果有,显示购物车中的全部物品,并且计算几个。

    在ShoppingCart中,我们每中物品只保存一次,然后更新它存在的个数。显示的时候,可以根据商品个数分别显示,也可以同种商品显示在一起。

    并且调用CartItem类的getSum方法计算出总价格。

    package com.cjg.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.cjg.bean.CartItem;
    import com.cjg.bean.ShoppingCart;
    
    public class GetShoppingCartServlet extends HttpServlet {
    
        /**
             * The doGet method of the servlet. <br>
             *
             * This method is called when a form has its tag value method equals to get.
             * 
             * @param request the request send by the client to the server
             * @param response the response send by the server to the client
             * @throws ServletException if an error occurred
             * @throws IOException if an error occurred
             */
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            response.setContentType("text/html; charset=utf-8");
            PrintWriter out = response.getWriter();
            doPost(request, response);
        
        }
    
        /**
             * The doPost method of the servlet. <br>
             *
             * This method is called when a form has its tag value method equals to post.
             * 
             * @param request the request send by the client to the server
             * @param response the response send by the server to the client
             * @throws ServletException if an error occurred
             * @throws IOException if an error occurred
             */
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            response.setContentType("text/html;charset=utf-8");
            System.out.println(request.getContextPath());
            PrintWriter out = response.getWriter();
            //获取session
            HttpSession session =request.getSession();
            
            //从session中取出购物车信息
            ShoppingCart cart=(ShoppingCart)session.getAttribute("shoppingcart");
            
            
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            if(cart==null){
                out.println("<h1>您的购物车为空<h1>");
                out.println("<a href="ShopCart/showMerchandise.jsp ">去买几件</a> ");
                return;
            }
            out.println("<h1>您的购物车信息:<h1>");
            out.println("<a href=${pageContext.request.contextPath()}+"/showMerchandise.jsp">再买点</a>");
            printCartItem(out,cart);
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
        /*
         * 显示购物车中的商品
         */
        private void printCartItem(PrintWriter out, ShoppingCart cart) {
    
            //创建一个购物车,用list接收全部上面的信息,然后循环输出出来。
            ArrayList<CartItem> items=cart.getCart();
            
            //定义一个商品对象,用于遍历的中转容器
            CartItem item=null;
            
            //定义表格,输出表头
            out.println("<table width="500" border="1" align="lefg" >" );
            out.println("<tr>");
                out.println("<td with="200">商品名称</td>");
                out.println("<td with="100">价格</td>");
                out.println("<td with="100">数量</td>");
                out.println("<td with="100">合计</td>");
                for(int i=0;i<items.size();i++){
                    out.println("<tr>");
                    item=items.get(i);
                    out.println("<td>"+item.getName()+"</td>");
                    out.println("<td>"+item.getPrice()+"</td>");
                    out.println("<td>"+item.getQuantity()+"</td>");
                    out.println("<td>"+item.getSum()+"</td>");
                    out.println("</tr>");
                }
            out.println("</tr>");
            
        }
    
    }
    View Code

    定义的javabean

    首先是商品类:

    package com.cjg.bean;
    
    public class CartItem {
        private String name;
        private int quantity;
        private double price;
        private String id;
        private String desc;
        private double sum=0.0;
        public CartItem(String id,String name,int quantity,double price){
            this.id=id;
            this.name=name;
            this.quantity=quantity;
            this.price=price;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getQuantity() {
            return quantity;
        }
        public void setQuantity(int quantity) {
            this.quantity = quantity;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getDesc() {
            return desc;
        }
        public void setDesc(String desc) {
            this.desc = desc;
        }
        public double getSum(){
            return this.quantity*this.price;
        }
        
    }
    View Code

    然后是购物车类:

    package com.cjg.bean;
    
    import java.util.ArrayList;
    
    import javassist.bytecode.Descriptor.Iterator;
    
    public class ShoppingCart {
        private   ArrayList<CartItem> cart;
        public ShoppingCart(){
            cart =new ArrayList<CartItem>();
            
        }
        public ArrayList<CartItem> getCart(){
            return cart;
        }
        public  void addItem(CartItem item){
            CartItem olditem=null;
            if(item!=null){
                for(int i=0;i<cart.size();i++){
                    olditem=cart.get(i);
                    if(olditem.getId().equals(item.getId())){
                        olditem.setQuantity(olditem.getQuantity()+item.getQuantity());
                        return;
                    }
                }
            }
            cart.add(item);
        }
        public boolean removeCartItem(String id){
            CartItem item=null;
            for(int i=0;i<cart.size();i++){
                item=cart.get(i);
                if(item.getId().equals(id)){
                    cart.remove(i);
                    return true;
                }
            }
            return false;
        }
        public double getTotal(){
    //        Iterator <CartItem> it = cart.iterator();
    //        double sum=0.0;
    //        CartItem item=null;
    //        while(it.hasNext()){
    //            item=it.next();
    //            sum=sum+item.getPrice();
    //        }
            double sum=0.0;
            CartItem item=null;
            for(int i=0;i<cart.size();i++){
                item=cart.get(i);
                sum=sum+item.getPrice();
            }
                
            return sum;
            
        }
    
    }
    View Code

    前台展示页:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'shoMerchandise.jsp' starting page</title>
    
    </head>
    
    <body>
        <table width=424 " height="583" border="0" align="center">
            <tr>
                <td width="190"><img alt="hpcomputer"
                    src="images/hppavilion.jpg"></td>
                <td width="224"><img src="images/lenovo.jpg">
                <td>
            </tr>
            <tr>
                <td>笔记本电脑</td>
                <td>移动硬盘
            </tr>
            <tr>
                <td>价格:5999.99元</td>
                <td>价格:688.88</td>
            </tr>
            <tr>
                <td>
                <a href="servlet/AddShoppingCart?id=0001&name=笔记本电脑&price=5999.00"><img src="images/buybutton.gif" width="71" height="21" border="0" /></a>
                </td>
                <td>
                <a href="servlet/AddShoppingCart?id=0002&name=移动硬盘&price=688.88"><img src="images/buybutton.gif" width="71" height="21" border="0"/></a>
            </tr>
        </table>
    </body>
    </html>
    View Code

     web.xml文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
      <servlet>
        <servlet-name>AddShoppingCart</servlet-name>
        <servlet-class>com.cjg.servlet.AddShoppingCart</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>GetShoppingCart</servlet-name>
        <servlet-class>com.cjg.servlet.GetShoppingCartServlet</servlet-class>
      </servlet>
    
    
      <servlet-mapping>
        <servlet-name>AddShoppingCart</servlet-name>
        <url-pattern>/servlet/AddShoppingCart</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>GetShoppingCart</servlet-name>
        <url-pattern>/servlet/GetShoppingCart</url-pattern>
      </servlet-mapping>
    
    </web-app>
    View Code
  • 相关阅读:
    php主要输出方式的区别
    文件操作
    会话
    Jquery常用函数及功能
    AJAX
    php 审核注册
    转载图片上传预览 代码
    php笔记-图片上传
    php 练习题-session与 cookie的 取值赋值
    php学习笔记-会话控制简单介绍session和cookie(一)
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/5811873.html
Copyright © 2011-2022 走看看