Java EE: 3. Graphic sessions and javaeesessions

Source: Internet
Author: User

Java EE: 3. Graphic sessions and javaeesessions

Writer: BYSocket)

Weibo: BYSocket

Bean flap: BYSocket

FaceBook: BYSocket

Twitter: BYSocket

After the Http protocol and graphic Cookie are illustrated one after another, they are lost! But I want to tell you why I like writing! Write it, learn from the old and learn from the old ~ Then write it to the old man! This series is designed to be simple and easy to understand'


I. Session Origin

HTTP is stateless, that is, each request is an independent thread. For example: In shopping, you have selected product A and added it to the shopping cart. This is thread. Then, select item B as the line B. But every time the thread is independent (for containers, A and B are different users), thread A does not know that there is B or B does not know. How to make payment together?

A: How do I save the status of multiple request sessions of the same user? Naturally, HTTPS ensures that the connection is secure and can be associated with a session.

The question is how to track the same user. There are many choices:

1. The EJB (stateful Session bean saves the session state) environment is harsh and requires a J2EE server with EJB, rather than a Web Container like Tomcat.

2. Databases (this seems omnipotent. For data)

3. We want to talk about httpaiesion, which stores the session Status of multiple requests across a specific user.

4. the HTTPS mentioned above is too harsh.

Ii. Session mechanism

Mechanism. Actually, it is to say something inside it. Mainly two W: What? How?

What is Session?

A Session represents a Session between the server and the client. It ends when the session expires (the server is closed) or the client is closed.

How does session works?

Sessions are stored on the server, and different users are differentiated by SessionID for each client (customer. Session is implemented by Cookie technology or URL rewriting. By default, the Cookie technology is used. The server creates a Cookie value for the JSESSIONID for this session.

Supplement:

In fact, there is also a technology: Form hidden fields. It can also implement the session mechanism. This is just a supplement. Before the server responds, it will modify the form and add a hidden field similar to sessionID so that this session can be identified when it is returned to the server.

This technology can also be used in Web security to effectively control cross-site Request Forgery of CRSF.

Iii. Detailed Seesion mechanism process

This is the detailed diagram of the First session Request. Using Cookie technology, I also wrote a small Servlet demo of HttpSessionByCookieServletT. java to simulate the lifetime of Seesion. The Code is as follows:

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 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 [2015] [Jeff Lee] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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 2015-7-12 10:58:28 * Default Cookie implementation case of HttpSession */@WebServlet(urlPatterns = "/sessionByCookie")publicclass HttpSessionByCookieServletT extendsHttpServlet {     privatestatic final long serialVersionUID = 1L;     @Override    protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp)            throwsServletException, IOException {                 // Obtain the session        // If this is the first request, an 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 the session Attribute Value            session.setAttribute("name""Jeff");        }        // Obtain the SessionId        String sessionId = session.getId();                 PrintWriter out = resp.getWriter();        // If httsponesion is created        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>");            // Obtain the attribute value from the Session            out.println("The second-response - name: "                    + session.getAttribute("name"));        }             }     }

Grand small advertisement:

The Code learned by the bricklayer is on github (synchronized with osc git). Welcome to star, give comments, and make progress together. Address: https://github.com/JeffLi1993

① The client sends the first request to the server

In this case, the client wants the server to set its name to the session.

② The container on the server generates the session object with the user's unique sessionID and sets the value

It can be seen from the code that a session object is generated by req. getSession () in the request. SetAttribute ("name", "Jeff"), key is string, and value is acceptable to all objects.

At this time, we no longer need to process the session through the cookie technology, and the container will help us deal with it.

③ Container response Set-Cookie: JSESSIONID =...

We can check the response in F12.

The result is that each Cookie's set has a header corresponding to the Set-Cookie. HttpOnly is the read-only mode of this Cookie. Only the unique session ID is JSESSIONID.

④ The browser parses the Cookie and saves it to the browser file.


The cookie file stored in the corresponding session is found. This file is protected and cannot be opened. The graphic Cookie shows you how to find the file.


What will happen to the second request?

Below, the bricklayer re-visits this address:

① Request again

In this case, the request has a Cookie value: JSESSIONID =... This value is sent to the server.

② The container obtains the SessionId
, Associate HttpSession

③ No SetCookie is returned.

However, in this request, we responded to the value of the set in the previous request. Jeff printed it!


The container will help you find the unique session Object Based on the Cookie.

The bricklayer's memory copy: Seesion mechanism. Remember the two request graphs.


Iv. Supplement

Click till now ~ Write in detail later. This figure is from the network


Bad guy is an attacker. Cross-Site Request Forgery. User requests are forged to pose threats to server data or users. Web security is gradually improved from these foundations.


V. Summary

1. describes the working mechanism of the session, which is related to some security issues. Remember what Seesion is, how to use it, and how to transmit it between the Server Client.

2. The Code learned by the bricklayer is on github (synchronized with osc git). Welcome to star, give comments, and make progress together. Address: https://github.com/JeffLi1993

Writer: BYSocket)

Weibo: BYSocket

Bean flap: BYSocket

FaceBook: BYSocket

Twitter: BYSocket

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.