Java Web Advanced Programming (II)

Source: Internet
Author: User
Tags http cookie session id send cookies java web

Use session to maintain status

First, session

In order to implement multiple requests associated with the same client and the sharing of data between these requests, the session is used to maintain the state between the request and the request. From the server's perspective, when the user's Web browser opens the first socket that is linked to the server, the request begins until the server returns the last packet and closes the link, and the request ends. There is no longer any connection between the user's browser and the server, and when the next link starts, the new request cannot be associated with the previous request.

Maintain status

The most classic example is that online shopping sites need to use a shopping cart to ensure that users and products are kept.

Remember users

Such an example is the User forum website, in multiple operations, the user only need to log in once.

Start a Task program workflow

When users are using a Web application to accomplish a task, they need some form of workflow, such as news release.

Second, use session cookies and URL rewriting.

A session is some file, memory fragment, object, or container that is managed by a server or Web application and contains a variety of different data that is assigned to it.

Usually the session is given a randomly generated string called the session ID. The session ID that is created is returned to the user's browser as part of the response the first time the session is created. The next request from the user's browser will include this session ID in some way. When an application receives a request that contains a session ID, it can associate an existing session with the current request through that ID.

Methods that implement session ID return from the server to the browser include session cookies and URL rewriting.

Session cookies

This technique is also called an HTTP cookie. Cookies are a necessary communication mechanism that can pass arbitrary data in the server and browser via the Set-cookie response header and are stored on the user's computer and then returned to the server from the browser via a request-header cookie. The cookie contains the domain name, path, expiration date, or maximum life cycle, security flags, or only HTTP flags. The name of the session cookie defaults to Jsessionid.

Domain will tell the browser which domain name the cookie should be sent to.

Path further restricts the cookie to a specific URL relative to the domain.

Expries defines the absolute expiration date of the cookie,

If there is a secure attribute, the browser will only send cookies over HTTPS for encrypted transmission.

HttpOnly restricts cookies to browsers and avoids JavaScript and flash.

The session ID in the URL

Another way to transfer the session ID is to use a different strategy for embedding and locating the session ID in the URL by url,web the server until you find a specific pattern that contains the session ID in the URL. In Java EE, the session ID is added to the argument of the last path segment of the URL, in this way the parameters of the meeting session ID and query string are detached. For example:

http://Www.example.com/supprot; Jsessionid=nrxclgg2vg7ki4mdlln?foo=bar

The session ID must be embedded in all URLs returned by the application, including links to pages, form actions, and redirects.

The HttpServletResponse interface defines two ways to rewrite URLs: Encodeurl and Encoderedirecturl, which embed the session ID in the URL when necessary.

Loopholes

Copy-and-paste errors, session pinning, cross-site scripting and session hijacking, unsafe cookies

Third, store data in the session

To configure a session in the deployment descriptor:

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

All <session-config> and <cookie-config> labels are optional and the function of the labels can be viewed separately. With the above configuration, the session timeout is 30min and only cookies are accepted for session tracking.

Storing, deleting, and retrieving data:

Create a map in the servlet that you can use to manipulate the data.

Private Final New Hashtable<>();      Public Storeservlet ()    {        this. Products.put (1, "sandpaper");          this. Products.put (2, "Nails");         this. Products.put (3, "Glue");         this. Products.put (4, "Paint");         this. Products.put (5, "Tape");    }

Use in the 1.doGet method:

@Overrideprotected voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {String action= Request.getparameter ("Action"); if(Action = =NULL) Action= "Browse"; Switch(action) { Case"AddToCart":                 This. AddToCart (request, response);  Break;  Case"Emptycart":                 This. Emptycart (request, response);  Break;  Case"Viewcart":                 This. Viewcart (request, response);  Break;  Case"Browse":            default:                 This. Browse (Request, response);  Break; }    }    Private voidAddToCart (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {intproductId; Try{productId= Integer.parseint (Request.getparameter ("ProductId")); }        Catch(Exception e) {response.sendredirect ("Shop"); return; } HttpSession Session=request.getsession (); if(Session.getattribute ("cart") = =NULL) Session.setattribute ("Cart",NewHashtable<integer, integer>()); @SuppressWarnings ("Unchecked") 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); Response.sendredirect ("Shop?action=viewcart"); }    Private voidEmptycart (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {request.getsession (). RemoveAttribute ("Cart"); Response.sendredirect ("Shop?action=viewcart"); }    Private voidViewcart (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {request.setattribute ("Products", This. Products); Request.getrequestdispatcher ("/web-inf/jsp/view/viewcart.jsp"). Forward (request, response); }    Private voidbrowse (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {request.setattribute ("Products", This. Products); Request.getrequestdispatcher ("/web-inf/jsp/view/browse.jsp"). Forward (request, response); }

Iv. clustering users who use sessions

Clustering adds redundancy and scalability to your application, and properly configured clustered applications that run correctly even when some of the servers are terminated, refer to the normal processing of user requests while performing routine maintenance work. Administrators can even upgrade the application and ensure that the application does not terminate processing of the request.

Advanced Message Queuing Protocol (AMQP), Java message Service (JMS), Microsoft message Queuing (MSMQ).

Issue: The way a Session object exists in memory and exists only in a single instance of the Web container, two successive requests from the same client will access different Web containers, while the first container assigns the ID and the second container is unrecognized.

Workaround: Use Sticky sessions: enable the load balancing mechanism to perceive the session and always send requests from the same session to the same server. (depending on load balancing techniques, such as the load balancer adding their own session cookies to the response and identifying those cookies in the request after the call).

Java Web Advanced Programming (II)

Related Article

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.