javaweb--using session to maintain state 2

Source: Internet
Author: User

In this case, a similar shopping cart function will be completed, when the customer visits the site, will select the goods they will buy, and the shopping cart will always maintain the status of the product, the session will be linked to select the first item (the first request), select other products (other requests) and payment and so on.

1. Configuring the session in Web. xml

  <Session-config>    <Session-timeout>30</Session-timeout>    <Cookie-config>      <http-only>True</http-only>    </Cookie-config>    <Tracking-mode>Cookies</Tracking-mode>  </Session-config>

With such a setting, sessions longer than 30 minutes will expire, use cookies for session tracking, and the session cookie from HttpOnly to true to resolve security issues.

2. Page logic

This demo has only two pages, the following are the two page previews:

    • The first page of the product listing page will have a click into the shopping cart link view cart, and a list of items, the name of the product can be clicked, then the item will be added to the shopping cart.

    • This is a preview of the shopping cart page, there will be a link back to the Product List page, followed by an empty cart that empties the shopping cart after a click, and then displays a list of the items in the cart and their number.

3. JSP

    • First the Item List page, after the View cart is clicked, the action will be placed in the Viewcart this variable will be used in the Doget method, where a map is used to record the item's number and name, and the action will be placed in AddToCart when clicked. ProductID will be assigned the ID of the product
<%@ PageImport= "Java.util.Map" %><!DOCTYPE HTML><HTML>    <Head>        <title>Product List</title>    </Head>    <Body>        <H2>Product List</H2>        <ahref= "<c:url value="/shop?action=viewcart "/>">view Cart</a><BR/><BR/>        <% @SuppressWarnings("Unchecked") Map<integer, String>Products = (Map<Integer, String>) Request.getattribute ("Products"); for (int id:products.keySet ()) {%><ahref= "<c:url value="/shop ">                    <C:paramname= "Action"value= "AddToCart" />                    <C:paramname= "ProductId"value= "<%= integer.tostring (ID)%>"/>                </C:url>"><%= Products.get(ID)%></a><BR/>        <%            }        %>    </Body></HTML>
    • This is the shopping cart page JSP, where there are two map,products is to record the product ID and name, cart record the product ID and the number of selected, then two links, the first link will be directly returned to the Commodity Chain List page, the second will empty the shopping cart, The specific implementation is to assign the action to Emptycart and then to the servlet.
<%@ PageImport= "Java.util.Map" %><!DOCTYPE HTML><HTML>    <Head>        <title>View Cart</title>    </Head>    <Body>        <H2>View Cart</H2>        <ahref= "<c:url value="/shop "/>The >product List</a><BR/><BR/>        <ahref= "<c:url value="/shop?action=emptycart "/>">empty Cart</a><BR/><BR/>        <% @SuppressWarnings("Unchecked") Map<integer, String>Products = (Map<Integer, String>) Request.getattribute ("Products"); @SuppressWarnings ("unchecked") Map<Integer, Integer>cart = (Map<Integer, Integer>) Session.getattribute ("cart");            if (cart = = NULL | | cart.size () = = 0) out.println ("Your cart is empty."); else {for (int id:cart.keySet ()) {out.println ("" +product S.get (ID) + "(Qty:" + cart.get (ID) + ")<BR/>"); }}%></Body></HTML>

4. Code Logic

    • The first is doget, depending on the value of Actiond, will call different methods
@Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {String action= Req.getparameter ("Action"); if(Action = =NULL) {Action= "Browse"; }        Switch(action) { Case"AddToCart":                //Add items to your shopping cart                 This. AddToCart (REQ,RESP);  Break;  Case"Viewcart":                //go to Shopping cart page                 This. Viewcart (REQ,RESP);  Break;  Case"Emptycart":                //Empty Shopping Cart                 This. Emptycart (REQ,RESP);  Break;  Case"Browse":            default:                //go to Product List page                 This. browse (REQ,RESP);  Break; }    }
    • These two methods will forward the request directly to the JSP and pass the products of the map object,
    Private voidViewcart (httpservletrequest req, HttpServletResponse resp)throwsservletexception,ioexception {req.setattribute ("Products", This. Products); Req.getrequestdispatcher ("/web-inf/jsp/view/viewcart.jsp"). Forward (REQ,RESP); }    Private voidbrowse (HttpServletRequest req, HttpServletResponse resp)throwsservletexception,ioexception {req.setattribute ("Products", This. Products); Req.getrequestdispatcher ("/web-inf/jsp/view/browse.jsp"). Forward (REQ,RESP); }
    • The AddToCart method will add the item in the request to the shopping cart, first get the product ID from the request header, and then call HttpServletRequest's GetSession method to get the session, GetSession there are two ways: getsession () and GetSession (Boolean). In other words, you can choose not to input parameters and enter True or False three, where GetSession () and getsession (true) effect is the same, if the session exists to return to an existing session, Creates a new session if the session does not exist (does not return null), and getsession (FALSE) returns a session if the session exists and returns NULL if it does not exist. Then query the cart attribute in the session, add the cart feature if it does not exist, and the cart is actually a map that stores the number of items based on the ID, if the cart does not have the number of items in the final set to 1, if there will be an increase of 1.
    Private voidAddToCart (httpservletrequest req, HttpServletResponse resp)throwsservletexception,ioexception {intproductId; Try{productId= Integer.parseint (Req.getparameter ("ProductId")); }Catch(Exception e) {resp.sendredirect ("Shop"); return; } HttpSession Session=req.getsession (); if(Session.getattribute ("cart") = =NULL) {Session.setattribute ("Cart",NewHashtable<integer, string>()); } Map<integer, integer> cart = (Map<integer, integer>) session.getattribute ("Cart"); if(!Cart.containskey (productId)) {Cart.put (productId,0); } cart.put (Productid,cart.get (productId)+ 1); Resp.sendredirect ("Shop"); }
    • Finally, the Emptycart method of emptying the cart, which will delete the cart in the session, to realize the function of emptying the shopping cart.
    Private void Emptycart (httpservletrequest req, HttpServletResponse resp)             throws servletexception,ioexception {        req.getsession (). RemoveAttribute ("cart");        Resp.sendredirect ("Shop?action=viewcart");    }

javaweb--using session to maintain state 2

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.