Java EE: Three, graphical session (sessions)

Source: Internet
Author: User

Directory

Java EE: First, illustrated HTTP protocol

Java EE: Second, graphic Cookie (cookies)

Java EE: Three, graphical session (sessions)

Overview

First, the origin of the session

Second, session mechanism

Iii. detailed introduction of the seesion mechanism process

Iv. Supplementary

V. Summary

Reference

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.

Second, session mechanism

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

What is the Session?

Sessions represent the process of a session between a server and a client . Until the session expires (the server shuts down), or the client closes at the end.

How does session works?

Session is stored on the server side , and for each client (customer), through the SessionID to distinguish between different users. 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.

Add :

There is actually another technique: the form hides the field . 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 technology, also can be used in web security, can effectively control CRSF cross-site request forgery .

Iii. detailed introduction of the 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:

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869 package org.servlet.sessionMngmt;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.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 *  HttpSession的默认Cookie实现案例 */@WebServlet(urlPatterns = "/sessionByCookie")public class HttpSessionByCookieServletT extends HttpServlet {    private static final long serialVersionUID = 1L;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {                // 获取session        // 如果是第一次请求的话,会创建一个HttpSeesion,等同于 req.getSession(true);        // 如果已存在session,则会获取session。        HttpSession session = req.getSession();                if (session.isNew()) {            // 设置session属性值            session.setAttribute("name""Jeff");        }        // 获取SessionId        String sessionId = session.getId();                PrintWriter out = resp.getWriter();        // 如果HttpSeesion是新建的话        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>");            // 从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.

Reference

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

Java EE: Three, graphical session (sessions)

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.