cookie - session

Recently, I am working with native developers to jointly develop an SDK. The SDK is a mix of native and H5. I need to set cookies in the background on my side to verify user information and user login status. Before using cookies, I used a wheel written by someone else. This time I need to build the wheel myself. During the actual development, I found that my web foundation is still not solid, and my understanding of cookies (including session) is superficial, so this During the 5.1 holiday, take the time to learn and summarize, and record the content down the road, so that you can revive and review it later. . .

1.cookie

Cookies are used to save session information. Because http is a stateless protocol, when the first request is disconnected and the same user requests the second time, if there is no such session mechanism, the server will not be able to identify the user at all. The session mechanism is actually a supplement and extension to the http protocol. The cookie and session are the main components of the session mechanism. The cookie is saved on the client side, and the session is saved on the server side. Although the storage place is different, the content of both is service. end to decide.

In general actual scenarios, the process of using cookies is as follows:

Step1: The client requests the server login interface.

Step 2: The server performs login verification. If the login verification is passed, the login information is used as the unique identifier of the client that initiated the request, and the information is set as the value of the cookie and returned to the client. This cookie information is Set_Cookie in the response header.

Step3: The client gets the "ID" assigned to itself by the server, then every time it requests the server, it will bring a cookie, and the cookie value is the cookie in the request header.

In general practice, you only need to build a wheel that adds cookies to reposnse on the server side.

cookie wheel code:

public void setCookie(HttpServletResponse resp, Map<String, ?> params) {
  if (params == null || params.isEmpty()) {
    return;
  }
  Set<String> keySet = params.keySet();
  Object obj = null;
  Cookie cookie = null;
  for (String key : keySet) {
    obj = params.get(key);
    if (obj != null && obj.getClass().isAssignableFrom(Cookie.class)) {
      cookie = (Cookie) obj;
    } else {
      cookie = new Cookie(key, URLEncoder.encode((String) params.get(key)));
  }
  cookie.setMaxAge( 60 * 60 * 24 * 30); // Set the valid time 
  cookie.setPath("/" );
  resp.addCookie(cookie);
  }
}

Cookies can also be used for browser behavior tracking (analyzing user browser behavior) and personalization (user browser customization settings, themes, etc.).

Simply for the client, cookies can actually be used for local storage, but if the client requests the data in the cookie every time, there will be additional performance overhead, especially on the mobile side, and now There are also more APIs for local web storage data, such as localstorage and sessionstorage added by h5. .

Web API interface for cookies: https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie 

 

2.session

The session is on the data server from beginning to end, and it is the "user ID" stored on the server. After each client successfully requests the server, the server must generate an id for the client, and this id will be returned to the client in the form of a cookie, so that the client will bring this sessionId in subsequent requests. The server locates the client information stored in the server according to this ID.

Taking the jsp page as an example, if there is no sessionId in the cookie, then jsp will create a session by default, and the default jsp tag is <%@ page session = true %>. And add the sessionId to the cookie.

As for creating a session on the server side, as long as the jar package of javax.servlet.http is introduced, the HttpSession object can be created directly. If it is in Sevelet, it will also automatically create a session. HttpSession session = request.getSession(); Force session, getAttribute(Stringkey) and setAttribute(String key, Objectvalue) methods to read and write session. Sessions store data in the form of key-value pairs.

session API http://docs.sqlalchemy.org/en/latest/orm/session_api.html

The role of the session is similar to that of the cookie. It is simpler to use than the cookie, but it will increase the pressure on the server. Generally, the session will be stored in the jvm, so the reading and writing speed will be very fast, but once the amount of data is huge, it will require a lot of heap space. Now there is a new service solution, which is to save the information of the Http Session independently - Spring Session link: http://www.infoq.com/cn/articles/Next-Generation-Session-Management-with-Spring-Session.

3 URL rewriting

URL rewriting is a solution for browsers that do not support cookies or when cookies are manually closed. I have not encountered such a situation in my actual development this time, but maybe I will encounter it in the future. I will post the code here.

The HttpServletResponse class provides encodeURL(Stringurl) to implement URL address rewriting

<td>
    <a href="<%=response.encodeURL("index.jsp?c=1&wd=Java") %>"> 
    Homepage</a>
</td>

 

and redirect

<%
 response.sendRedirect(response.encodeRedirectURL(“administrator.jsp”));
        return;
%>

 

Of course, you can use some framework-encapsulated href functions, or jst tags. . . . . Rewriting will help you determine whether the browser supports cookies. If not, the value of sessionId will be spliced ​​to the back of the url and passed to the server.

The above is just a brief overview of the personal perspective of cookies and sessions. Some very important API methods are just posted with links, just to explain the concepts as roughly as possible. After all, the code is also a concrete demonstration of excellent design ideas. I think I understand the idea behind it. That's what matters in the end.

 

Guess you like

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