State management (Cookie, Session)

state management

Why you need state management

Web applications communicate using the HTTP protocol , and the HTTP protocol is a "stateless" protocol, that is, once the server has responded to the client's request, it disconnects the connection, and the next request from the same client will re-establish the connection;

·The server application sometimes needs to determine whether the request is sent by the same customer, for example, the customer purchases products multiple times. Therefore, it is necessary to keep track of a series of requests made by the same client;

what is state management

Treat multiple interactions (one request, one response) between the client (browser) and the server as a whole, and save the data involved in multiple interactions, that is, the state

State refers to data

Management refers to the modification of data over multiple interactions

Two common patterns of state management

· Client-side state management technology: save the state on the client side. Typically cookie technology;

· Server state management technology: save the state on the server. The representative is Session technology;

Cookie

What are cookies

When the browser sends a request to the web server, the server will send a small amount of data to the browser in the form of a set-Cookie header, and the browser will save the data; when the browser accesses the server again, it will save the data Sent to the server in the form of a Cookie header ;

The principle of cookies

How to create cookies

· The Servlet API provides javac.servlet.http.Cookie for using cookies;

Create :

//name: The name used to distinguish different cookies
//value: the value of the cookie
Cookie c = new Cookie(String name,String value);
response.addCookie(c)

How to query cookies

Get all the Cookie objects of the client:

Cookie[]request.getCookies();

Note: This method may return null;

Get the name or value of a Cookie object:

String Cookie.getName();
String Cookie.getValue()

How to modify cookies

· step1, get all cookies sent by the client;

· step2, find the cookie to be modified according to the name;

· step3, call the setValue (String newValue) method of the cookie to modify the value of the cookie;

· step4, add the modified cookie to the response and send it to the client;

Code:
Cookie[] cookies = request.getCookies();
if(cookies!=null){
    for(Cookie c:cookies){
        String name = c.getName();
        if(name.equals("city")){
            c.setValue("Shanghai");
            //The cookie with the same name will be overwritten to achieve the purpose of modification
            response.addCookie(c);
        }
    }
}

Cookie time to live

By default, the browser will save the cookie in the memory, as long as the browser is not closed, the cookie will always exist ;

· If you want the cookie to remain after closing the browser, you can set the expiration time;

//seconds unit is seconds, the precision is not very high
void Cookie.setMaxAge(int seconds)

· seconds>0: The maximum time for the browser to save the cookie is the set parameter value. If the specified time is exceeded, the browser will delete the cookie. This cookie is stored on the hard drive;

· seconds=0: delete the cookie; after modifying the lifetime of the cookie to 0, the original cookie will be replaced with the response sent back to the client, and the cookie will be deleted due to the expiration of the life cycle;

seconds<0: the default value, the browser will save the cookie to memory;

Cookie encoding

· Cookie can only save legal ASCIIZIFU; if you want to save Chinese, you need to replace Chinese with legal ASCII characters, that is, encoding;

Cookie c = new Cookie(
    "city",URLEncoder.encode("北京","utf-8")
);

Cookie decoding

In order to see the actual Chinese , the decoded cookie needs to be restored and displayed;

Cookie[]Cookies = request.getCookies();
if(Cookies!=null){
    Cookie c = new Cookie[0];
    String value = c.getValue();
    //Consistent with the encoding format
    value = URLDecoder.decode(value,"utf-8");
}

Cookie path problem

What is a cookie path

When the browser accesses an address on the server, it will compare whether the path of the cookie matches the path, and only the matching cookie will be sent to the server;

The default path of the cookie is equal to the path of the web component that added the cookie;

· For example: /appName/file/addCookie.jsp adds a cookie, then the path of the cookie is equal to /appName/file

Conditions for sending cookies

The address to be accessed must be the path of the cookie or its sub-path before the browser will send the cookie;

· Such as:

 - The path to the cookie is /appName/file

 - A cookie will be sent when accessing /appName/file/a.jsp or /appName/file/b.jsp;

 - No cookies will be sent if /appName/c.jsp is accessed;

How to set cookie path

· Use the following code snippet to set the path of the cookie

Cookie c = new Cookie("uname","jack");
c.setPath("/appName");
response.addCookie(c);

Cookie restrictions

· Cookies can be disabled by the user;

Cookie will save the state on the browser side, which is not safe; for sensitive data, it needs to be encrypted before using cookie to save;

· Cookies can only save a small amount of data, about 4KB;

· The number of cookies is limited;

· Cookies can only save strings;

Session

what is session

When the browser accesses the web server, the server will allocate space for each browser in the server's memory, and create a separate Session object . This object has an Id attribute whose value is unique, generally called SessionId , and the server will This SessionId (using a cookie) is sent to the browser; when the browser accesses the server again, it will send the sessionId to the server, and the server can find the corresponding Session object according to the SessionId;

How Session Works

How to get Session

method one:

HttpSession s = request.getSession(boolean flag);

HttpSession is an interface, and it returns an object that conforms to the interface specification ;

· When the flag is true: first check whether there is a SessionId in the request, if there is no SessionId, the server will create a Session object; if there is a SessionId, look up the corresponding Session object according to the SessionId, and return if found; if not found, create a new one Session object, so when the flag is true, a Session object must be obtained;

· When the flag is false, if there is no SessionId and there is a SessionId but no Session object is found, both return null; if found, return;

Method two:

HttpSession s = request.getSession();

· Equivalent to request.getSession(true);

· This method is provided to make code writing more convenient. In most cases, it is necessary to return a Session object regardless of whether it is found or not;

How to bind objects using Session

· Binding object:

void Session.setAttribute(String name,Object obj);

Get the binding object:

Object Session.getAttribute(String name);

· Remove binding object:

Void Session.removeAttribute(String name);

Note: The return value of the getAttribute method is of type Object, which needs to be converted to the data type when removing data, and must be consistent with the data type we stored;

Immediately delete the Seeson object :

Session.invalidate()

Seesion Verification

When users access resources that need to be protected, they can use session authentication to ensure their security, such as resources that can only be accessed after login;

· To implement Session authentication, follow these steps:

 - 1. Use Session.setAttribute() to bind data first;

 - 2. Use the Session.getAttribute() method to read the binding value, if not, jump to the login page;

Session timeout

What is session timeout

The Web server will delete the Session objects that have been idle for too long to save server memory space resources;

· Web server default timeout limit: generally 30 minutes;

How to Modify the Default Time Limit of a Session

method one:

· By modifying the settings of the conf/web.xml file in tomcat

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

Method two:

void session.setMaxInactiveInterval(int seconds);

Consequences of disabling cookies in your browser

· If the browser disables cookies, the session cannot be used; but it can be solved in other ways;

· By default, the server will use Cookie to send the SessionId to the browser. If the user disables cookies, the SessionId will not be saved by the browser. In this case, the server can use such as URL rewriting to send SessionId;

URL rewriting

What is URL Rewriting

When the browser accesses an address on the server, it no longer uses the original address, but uses the modified address (that is, adds the SessionId to the original address);

How to implement URL rewriting

· If it is a connection address and form submission , use response.encodeURL(String url) to generate the rewritten URL;

· If it is a redirect , use response.encodeRedirectURL(String url) to generate the rewritten URL;

Session pros and cons

· advantage

  - Safe (save state on the server side);

  - Session can save more types of data, cookies can only save strings;

  - Session can save more data, Cookie is only about 4KB;

· shortcoming

  - Session saves the state on the server side and occupies server memory. If the number of users is too large, it will seriously affect the server performance;

The difference between session and cookie

(1) Session is stored on the server side, the client cannot know the information, and the security is higher; while the cookie is stored on the client side, the server can know the information;

(2) Session saves objects, while cookies can only save strings;

(3) Session does not distinguish paths. During the same user on the same website, all sessions are common in any place, while cookies distinguish paths. If the path parameter is set, then the same website under different paths. Cookies are mutually inaccessible;

(4) Session can save more data, while Cookie can only save about 4KB;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944278&siteId=291194637