Using session technology to realize the function of shopping cart in the online mall

Source: Internet
Author: User

First, simply understand the difference between a session and a cookie:

The difference between a session and a cookie:

Session is the user's first write to the user exclusive session (server side)

A cookie is a browser that writes the user's data to a user.

The session object is created by the server and the developer can invoke the GetSession method of the request object to get the session object.

Write the page code first, still use the product browsing record to write:

1, the JSP purchase page code is as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><% @page import=" java.util.* "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

2. Create a servlet page for the item's browsing history

Package Cn.itcast.cookie;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import javax.servlet.http.HttpServletRequest;    Import Javax.servlet.http.httpservletresponse;public class Addcookie extends HttpServlet {//Get user current access to product, update to product browsing History list public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcepti        on {//Auto refresh Response.setheader ("Refresh", "2;url=/myday07/products1.jsp");        1. Get current user Browse commodity id String id = request.getparameter ("id");        2. Access to user browsing record list cookie[] cookies = request.getcookies ();        Find Access record list name:visitlist-----1,3,5,6 String visitlist = null; if (cookie = null) {//exists cookie for (cookie:cookies) {if (Cookie.getname (). Equals ("                    Visitlist ")) {visitlist = Cookie.getvalue ();                Break }           if (visitlist = = null) {//list does not exist, current product first item cookie cookie = new Cook                IE ("visitlist", id);                Cookie.setmaxage (60 * 60);                Response.addcookie (cookie);            Response.getwriter (). println ("add success");                } else {//3, judging if the current item is already in the list string[] Existids = Visitlist.split (","); for (String exsitid:existids) {if (Exsitid.equals (ID)) {//ID exists in the list response                        . Getwriter (). println ("add success");                    Return }}//4, if the current product is not in the list, add to the list cookie cookie = new Cookie ("Visitlist", visitlist                + "," + ID);                Cookie.setmaxage (60 * 60);                Response.addcookie (cookie);            Response.getwriter (). println ("add success"); }} else {//indicates that there are no cookie cookie cookies for the site = new CooKie ("visitlist", id);            Cookie.setmaxage (60 * 60);            Response.addcookie (cookie);        Response.getwriter (). println ("add success");  }} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception,    IOException {doget (request, response); }}

3. Write a cookie page that clears the cache

Package Cn.itcast.cookie;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.httpservletresponse;public class ClearCookie extends httpservlet{public    void Doget ( HttpServletRequest request, HttpServletResponse response)            throws Servletexception, IOException    {        Cookie Cookie=new Cookies ("Visitlist", "" ");        Cookie.setmaxage (0);        Response.addcookie (cookie);        Response.sendredirect ("/myday07/products1.jsp");            }    public void DoPost (HttpServletRequest request, httpservletresponse response)            throws Servletexception, IOException    {        doget (request, response);}    }

4, write the product purchase page

Package Cn.itcast.cookie;import Java.io.ioexception;import Java.util.hashmap;import java.util.map;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;public class Buysession extends httpservlet{//Add Item to Shopping cart public void doget (HttpServlet        Request request, HttpServletResponse response) throws Servletexception, IOException {//1. Get the ID of the product        String id=request.getparameter ("id");        2. Get the shopping cart cart--from the session to get HttpSession session=request.getsession (); Map<string, integer> cart= (map<string, integer>) session.getattribute ("cart");//If there is no shopping cart in the session if (car        T==null) {//The original session does not exist in the shopping cart cart=new hashmap<string, integer> (); }//3. Determine if the item exists in the shopping cart if (Cart.containskey (ID)) {//4. Number of +1 int number=cart.get (ID         );   Cart.put (ID, number+1);        }else{//5. There is No 1 cart.put (ID, 1) in the number of items deposited into the shopping cart;                } session.setattribute ("cart", cart); Response.sendredirect ("/myday07/products1.jsp");//redirect Back} public void DoPost (httpservletrequest Request, HttpServletResponse response) throws Servletexception, IOException {doget (Request, response    ); }}

The final effect is as follows:

Using session technology to realize the function of shopping cart in the online mall

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.