Java EE to understand the small things: three, the diagram session (session)

Source: Internet
Author: User

writer:bysocket (mud and brick pulp carpenter)

Micro-Blog: Bysocket

Watercress: Bysocket

FaceBook: Bysocket

Twitter: Bysocket

successively schematic HTTP protocol and graphic cookies , the middle of the confusion period ha, did not write! But you have to tell yourself clearly like to write why not write! Then write, learn to learn old ~ and then write to the old! This series is based on the chart , and strive to be simple and understandable , "


First, the origin of the session

http is stateless , which means that each request is a separate thread. For example: In the shopping, you choose a product, add to the shopping cart, this is a thread. Then select the B product is the B thread. But each time the thread is independent (for the container, a, B becomes a different user), thread A does not know that there is a b,b or a. How to pay together?

Jan said: How to save the same user multiple request session state ? Natural HTTPS ensures that the connection is secure and that it can be associated with a session.

the problem is how to track the same user and choose a lot of nature:

1.EJB(stateful session Bean Save session state) environment requires the Java EE server with EJB instead of the Web container such as Tomcat.

2, the database (this seemingly omnipotent. For data)

3, is the httpseesionwe want to speak, save the session state of multiple requests across a specific user .

4, the above said HTTPS, the conditions are too harsh.

two, session mechanism

Mechanism, what words are a bit tall. In fact, it is to say something inside it. Main two w:what? How?

What's the Session?

The

Session represents the server and client a session process. Until the session expires (the server closes) or client shuts down ends.

How does session works?

Session is store on server , and for each client (customer), differentiate different users by SessionID. Session is implemented with cookie technology or URL rewriting. By default, the cookie technology is implemented, and the server will create a Jsessionid cookie value for this session.

Supplement :

form hidden fields /strong>. It can also implement the session mechanism. Just as a supplement, the server responds by modifying the form form and adding a sessionid-like hidden field that can be flagged when it is passed back to the service.

This technique can also be used on web security to effectively control CRSF cross-site request forgery .

three, details seesion mechanism process

This is the detailed diagram of the first request of the session. With Cookie technology, I also wrote a Httpsessionbycookieservlett.java servlet demo, simulating the life of seesion. The code is as follows:

PACKAGEORG.SERVLET.SESSIONMNGMT; Importjava.io.ioexception;importjava.io.printwriter; Importjavax.servlet.servletexception;importjavax.servlet.annotation.webservlet; Importjavax.servlet.http.httpservlet;importjavax.servlet.http.httpservletrequest; importjavax.servlet.http.httpservletresponse;importjavax.servlet.http.httpsession;/* * Copyright [] [Jeff Lee] * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applicab Le law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without WAR Ranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. *//** * @author Jeff Lee * @since The default cookie implementation case for 2015-7-12 10:58:28 * httpsession */@WebServlet(Urlpatterns = "/sessionbycookie") Publicclasshttpsessionbycookieservlett Extendshttpservlet {     Privatestaticfinallongserialversionuid = 1L; @Override Protectedvoiddoget (httpservletrequest req, HttpServletResponse resp) throwsservletexception, IOEXC        eption {//Get session//If this is the first request, a httpseesion will be created, equivalent to Req.getsession (true);        If a session already exists, the session is obtained.                 HttpSession session = Req.getsession ();        if (Session.isnew ()) {//Set Session property value Session.setattribute ("name", "Jeff");                 }//Get sessionId String sessionId = Session.getid ();        PrintWriter out = Resp.getwriter (); If Httpseesion is new, if (Session.isnew ()) {out.println ("hello,httpsession!        <br>the First response-seesionid= "+ sessionId +" <br> "); } else{out.println ("hello,httpsession!            <br>the Second Response-seesionid= "        + sessionId + "<br>");         Gets the attribute value from session out.println ("The Second-response-name:" + session.getattribute ("name")); }             }     }


Play a small ad:

Masons learn the code on GitHub (synchronous osc git), welcome to Point Star, suggestions, progress together. Address: https://github.com/JeffLi1993

① client sends the first request to the server

At this point, the client wants the server to have its name set to the session.

The container on the ② server produces the user's only SessionID session object and sets the value

It can be seen from the code that by Req.getsession () from the request, the freshman becomes a session object. and set the setattribute ("name", "Jeff"), the key is String,value is the object can be.

At this time, we do not have to use the session through the cookie technology, the container to help us deal with .

③ container response set-cookie:jsessionid= ...

We can F12 to see this response.

Can be obtained, each cookie set, has a corresponding Set-cookie head. HttpOnly This cookie is read-only mode. Just the session unique identifier is:jsessionid

④ Browser parses the cookie and saves it to the browser file.


, a cookie file is found for the corresponding session store. The file is protected and cannot be opened. A graphical cookie teaches you how to find the file.


What changes will be made to the second request?

below, Mason re-visited this address:

① Request again

At this point, the request will have a cookie value:jsessionid= ... This value is passed to the server

② Container Get SessionID
, Association HttpSession

③ Response No Setcookie at this time

But this request, we respond to the value of the last request set. Jeff will print it out!


For the server to get the session, that is, to get the session object from the request, the container will help you find the unique session object based on the cookie.

Mason Memory Small copy: Seesion mechanism, remember two times the request diagram can be.

Iv. Supplementary

Donuts ha ~ after the detailed writing. This figure is from the network


Bad guy , that's the attacker. Cross-site request forgery, forgery of user requests to create threats to server data or users. Web security is also a gradual improvement from these foundations.


V. Summary

1. The working mechanism of the session is described roughly, and some safety related. Remember what seesion is, how it is used, and how it can be transferred between server clients.

2, Masons learn the code are on GitHub (synchronous osc git), welcome to Point Star, suggestions, progress together. Address: https://github.com/JeffLi1993

writer:bysocket (mud and brick pulp carpenter)

Weibo: Bysocket

Watercress: Bysocket

Facebook:bysocket

Twitter:bysocket

Java EE to understand the small things: three, the diagram session (session)

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.