cookie simple and practical to use

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_35488412/article/details/60962153

The origin of the cookie:      

      In the program, session tracking is a very important thing. In theory, a user requests that all operations should belong to the same session, and another user requests for all operations should belong to another conversation, the two can not be confused. For example, any user A commodity purchased in a supermarket A shopping cart should be placed, whether it is time to buy what the user A, which belong to the same session, the user can not be placed B or C user's shopping cart it does not belong to the same session.

        The Web application is to use the HTTP protocol for transferring data. 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. That person 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. To track the session, a mechanism must be introduced.

       Cookie is one such mechanism. It can compensate for the lack stateless HTTP protocol. Before Session appears, essentially all of the sites use to track Cookie session.


By the JSP <% java code%> embodiment, the cookie provided therein. HTML, then we need to set and get with JS. Java code is shown below:

Set cookie: 

Cookie mycookie=new Cookie("cookieName",username+"#"+birthday+"#"+mail);      // 新建Cookie      

cookie.setMaxAge (60 * 60 * 24 * 365); // set the life cycle, in seconds

response.addCookie (MyCookie);               // output to the client

 

Receiving a cookie:

String[] info =new String[]{ "", "", ""};

Cookie[] cook=request.getCookies();

If(cook!=null){

for(int i=0; i<cook.length; i++){

if(cook[i].getName().equals("cookieName")){

info = cook[i].getValue().split("#")   

  }

}

[1], Info [2] obtained in this way the value stored in the cookie // Finally info [0], info.


Guess you like

Origin blog.csdn.net/qq_35488412/article/details/60962153