Get to know the difference between a text and usage of Session and Cookie

1. Session, what is Cookie

1.1 conceptual understanding

To understand what the session cookie and that one should first understand the following concepts.

1.1.1 stateless HTTP protocol

Agreement: refers to the conduct rules or regulations necessary to communicate to abide by computer communication networks between two computers.

Hypertext Transfer Protocol (HTTP): is a communication protocol that allows Hypertext Markup Language (HTML) documents transferred from the Web server to the client browser.

HTTP protocol is stateless protocol. Once the data exchange is completed, the client and server-side connection will be closed again to exchange data need to establish a new connection. This means that the server can not connect from a session on the track.

1.1.2 Session (Session) tracking

Session: refers to a series of actions after the user logs on site, such as browser add items to the shopping cart and purchase. Session (Session) Web tracking program is a common technique used to follow the conversation of the user. Common conversation tracking technology is Session and Cookie. Session to determine the user identity by recording the information on the server side, Cookie information recorded by the client to determine the user's identity.

1.2 Cookie

Since HTTP is a stateless protocol, a single server from the network connection can not know the identity of customers. A buys one item in the shopping cart, purchase goods again when the server has been unable to determine whether the purchase is part of a session or a user session B of the user A's. How to do it? The client who gave it issued a permit, a person, no matter who visit must bring their own passport. So that the server can confirm the identity of customers from the pass. This is the working principle of Cookie.

Cookie is actually a short text message. Client requests the server if the server requires the user to record the state, issued a response on the use of Cookie to the client browser. Cookie client will be saved.

When a browser requests that site again, the browser URL along with the request submitted with the Cookie to the server. The server checks the Cookie, in order to identify user state. The server can also modify the contents of Cookie needed.

1.2.1 Session Cookie and Cookie persistence if not set the expiration time, then the lifetime of the cookie for the duration of the browser session, close the browser window, cookie disappears. This period of life of the browser session cookie is called a session cookie. Session cookie is generally not stored on the hard but kept in memory, of course, such behavior is not the norm prescribed.

If you set an expiration time, the browser cookie will be saved to your hard drive, open the browser again after closing, these cookie remain valid until the expiration time exceeds the set. cookie stored on the hard disk can be shared between different processes browsers. This is called Persistent Cookie.

1.2.2 Cookie has a non-cross-domain nature

That is, the browser access Baidu will not take Google's cookie

1.3 Session

Session recording is another mechanism of customer status, except Cookie is stored in the client browser, and Session saved on the server. The client browser access to the server, the server to the client record information in some form on the server, this is the Session. Just look for the Session of the client when the client browser access again from the state on it. Each user accessing the server will establish a session and automatically assign a SessionId, used to uniquely identify a user's identity.

1.3.1 two questions

1) How SessionId regard to the server it automatically on every request?

That is a cookie, if you want the user to establish a session, you can return a unique cookie in the user authorization is successful. When a user initiates a request, the browser will automatically attached SessionId user information in the HTTP header (which is an automatic function of the browser, the user will not be aware, the developer also does not need operation), when the server processes the after the request, the results are returned to the corresponding user SessionId.

2) storing information required.

SessionId server via a key, to read and write the corresponding value, which achieve the purpose of maintaining session information.

1.3.2 Session of creation

When a program needs to create a session for the request of a client, the server first checks whether the client's request had contained the sessionId, if already contains the previously already created session for this client instructions, the server according to sessionId this session retrieved using (not retrieved, it will create a new), if the client request does not contain sessionId, create a session for this client and generates a session associated with this

sessionId associated, a value is neither sessionId repeated, not easy to find a replica of the law of string, the sessionId will be returned to the client stored in this response.

1.3.3 Disabling cookie

If the client is disabled cookie, usually there are two ways to achieve without relying session cookie.

1) URL rewriting. SessionId is to directly appended to the URL path.

2) hidden form field. The server will automatically modify the form, add a hidden field to be able to sessionId back to the server when the form is submitted.

such as:

<form name="walking-form" action="/xxx/xxx"> 
    <input type="hidden" name="JSessionId" value="NaOw3vjFW75aKnsF2C2HmdnV9LZcEbzWoWiBdHnLerjQ99zmpQng!-142002807"> 
    <input type="text"> 
</form>
复制代码

4, Session sharing for multi-site (the same parent domain different sub-domains) single server, we need to address is from SessionId shared between different sites. Due to the different domain name ( aaa.walking.com and bbb.walking.com ), while SessionId they are stored in their own cookie, so the server will think to visit two sub-stations, from different sessions. The solution is to modify the cookies of the domain name for the parent domain to achieve the purpose of the cookie sharing to achieve SessionId share (non-clustered server session share). Evils that, cookie information between sub-stations were also shared.

1.4 application scenarios

Visit the website, now enter a user name password, and then open the next day in many cases directly open. This time a mechanism used is the cookie. The scene is a shopping cart session, added at the client after the commodity can know what added goods, and how to distinguish it on the server side, so it needs to store some information on the use of the session.

2. how to operate Session

In Java Web development, Session provides a lot of convenience for us, Session is made between the browser and server maintenance. In traditional java web development, we implement the client and server to Http protocol interaction by implementing javax.servlet.Servlet interface or inherit javax.servlet.http.HttpServlet.

2.1 operating the Session API

Session operation is as follows:

@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpSession session = request.getSession();
    
    session.setAttribute("userName","walking");//设置属性
    session.setMaxInactiveInterval(30*60);//过期时间 单位秒
    session.getCreationTime();//获取session的创建时间
    session.getLastAccessedTime();//获取上次与服务器交互时间
    String id = session.getId();//获取sessionId
    int timeout = session.getMaxInactiveInterval();//获取session过期时间
    session.invalidate();//销毁session
}
复制代码

When the client and server to maintain user information there is a time limit, because the client for a long time (sleep time) did not interact with the server, the session is considered expired, Session destroy this server, client and server interaction again before the Session does not exist. That's session expired.

2.2 Setting Session expiration time

2.2.1 traditional web project set Session expiration time

1, is provided in web.xml session-config

as follows:

<session-config>
      <session-timeout>2</session-timeout>
</session-config>
复制代码

That is, the client and server interaction twice the longest interval of 2 minutes, 2 minutes session.getAttribute () Gets the value is null. The original session have been destroyed, from the new session in acquiring the property value is set before the naturally empty.

2, in the Tomcat in /conf/web.xml

session-config, the default value: 30 minutes

<session-config>
     <session-timeout>30</session-timeout>
</session-config>
复制代码

3, is provided in the Servlet

HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);//单位为秒
复制代码

2.2.2 SpringBoot project settings Session expiration time

2.3 Description

1. Priority: Servlet API provided in> Settings program /web.xml> Tomcat / conf / web.xml provided

2. (time between the visit and the last access time interval is greater than the maximum session inactive) If the access server overtime session, that is the end of the last session, but the server and the client will generate a new session, before the session where property values ​​are lost, resulting in new sesssionId

3. The client and server once an effective session (session has not timed out), each time the same access sessionId, if the code is set session.setMaxInactiveInterval () value, a maximum inactivity interval the session is to be modified, and applied as a the new value.

4.Session destruction (the end of the session on behalf of cycles): in a period called a request session.invalidate () method, the end of this period the request, session is destroyed; or automatically destroyed after the session timeout; client or off out browser

5. For the JSP, if you specify <% @ page session = "false"%>, you can not directly access the built-in JSP session variables, but also will not take the initiative to create a session, because the JSP is not performed automatically request.getSession () operation to obtain session.

3. Operation Cookie

3.1 server operating Cookie

As mentioned above, each time the client server will request information into the cookie header header information, we can get all the cookie object by HttpServletRequest.getCookies () method returns the cookie to end customers through addCookie method HttpServletResponse object.

API specific operation is as follows:

Cookie[] cookies = request.getCookies();//request对象获取所有cookie
for (Cookie cookie : cookies) {
    String name = cookie.getName();//cookie name
    String value = cookie.getValue();//cookie value
    String domain = cookie.getDomain();//域名
    int maxAge = cookie.getMaxAge();//过期时间
    boolean secure = cookie.getSecure();//浏览器通过安全协议发送cookies 返回true
    String comment = cookie.getComment();//描述
    int version = cookie.getVersion();//版本
    //以上除name属性都有对应set方法

    boolean httpOnly = cookie.isHttpOnly();//是否Httponly
    cookie.setHttpOnly(true);//设置Httponly值
}
//new cookie对象
Cookie cookie = new Cookie("userName","walking");
cookie.setPath("/");
cookie.setMaxAge(60*30);//30分钟
response.addCookie(cookie);//回写给客户端浏览器
复制代码

3.2 front-end operations cookie

Create a front-end set a cookie

/**
 * 创建并设置cookie
 * @param name cookie名称
 * @param value cookie值
 * @param expires 过期时间 毫秒 不填则默认30分
 */
function Setcookie(name, value, expires) {
    //设置名称为name,值为value的Cookie
    expires = expires || 30* 60 * 1000;
    var expdate = new Date();   //初始化时间
    expdate.setTime(expdate.getTime() + expires);   //时间
    //即document.cookie= name+"="+value+";path=/";   时间可以不要,但路径(path)必须要填写,
    // 因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!~
    document.cookie = name + "=" + value + ";expires=" + expdate.toGMTString() + ";path=/";
}
复制代码

Front-end acquisition cookie property value

/**
 * 获取对应cookie属性的value
 * @param c_name cookie属性name
 * @returns {string} cookie value
 */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
复制代码

4. Summary

1, cookie data is stored on the customer's browser, session data on the server.

2, cookie is not very safe, people can analyze the local cookie store and cookie deception, taking into account the security should be used session.

3, session will be stored on the server within a certain period of time. When accessing the increase will compare the performance of your server footprint, taking into account mitigating server performance, you should use the cookie.

4, a single cookie stored data can not exceed 4K, many browsers are limited to a maximum of 20 sites saved cookie.

5, consider storing login information and other important information for the session, additional information if necessary, they can be placed in a cookie.

6, the program development process, we can check every interaction with the server at the client the SessionID (Session attribute value, the non HttpServlet development environment may also be replaced with other Key value) for session management.

Description link

Guess you like

Origin juejin.im/post/5d8330996fb9a06b1d217bf5