Use cookie management user session state

    HTTP protocol is stateless, the server is unable to obtain the user's identity information, but in practical application scenarios we need a server can tell the user identity information so when it was suggested that the user first accesses the server can put some users status information back to the browser, the browser to carry user identity information returned by the server in the request the next time you access the server so that the server can determine the identity of the user. This user's identity is the cookie. The official definition of explanation given below: Cookie, sometimes with plural forms  Cookies , refers to the data (typically encrypted) to identify the user identity of certain sites, for tracking purposes session stored on the user's local terminal.

    A, cookie principles

    Cookie is to define the nature of a number of HTTP request and HTTP response header header, HTTP header information by the server so that the client can interact with the state. I use a diagram to represent the process of cookie created:

 

 (Source: https:? //Upload-images.jianshu.io/upload_images/13949989-dcf024be2733e725.png imageMogr2 / auto-orient / strip | imageView2 / 2 / w / 400 / format / webp). In java web development, we use HttpServletRequest HttpServletResponse objects and objects to create and access cookie. code show as below:

public class TestCookieServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
         doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("content-type","text/html;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PrintWriter out =  response.getWriter();
        Cookie[] cookies =  request.getCookies();
        if(cookies!=null){
            String cookieValue = null;
            for (Cookie cookie : cookies) {
                if("last_time".equalsIgnoreCase(cookie.getName())){
                    cookieValue =cookie.getValue ();
                     BREAK ; 
                } 
            } 
            out.print ( "time of your last visit is:" + cookieValue); 
        } the else { 
            out.print ( "! Welcome to the site" ); 
        } 
        Cookie the cookie = new new Cookie ( "Last_time", smf.format ( new new a Date ())); 
        cookie.setMaxAge ( -1 ); 
        response.addCookie (Cookie); 
        the out.close (); 
    } 
}

HttpServletResponse object added by addCookie (Cookie cookie) method cookie information into the response header, HttpServletRequest objects acquired by the getCookies cookie array () method. Cookie constructor initializes the object by key value of name-value pairs, obtain the cookie name and value getName values ​​and getValue methods. It should be noted cookie object getMaxAge (int i) method, which is the expiration time is used to set a cookie, and if set to -1 indicates the Cookie Cookie is a temporary, not persisted only in this browser window or child window of this window that opens effective, the Cookie fail immediately after closing the browser; if set to 0 immediately delete the cookie. HttpServletResponse object and does not provide such a method setCookie, if you need to modify the value of the cookie only need to be covered. The above code indicates the time of recording the user's last visit, the first visit if the user is welcome to visit the site is displayed.

 

 Adds information in the cookie response header when a user first visit, when the user's second visit to: request header will carry the cookie information.

 Finally, when using cross-domain cookie must pay attention to the problem of reading and writing, because cookie to meet the same origin policy, if you want to write cross-domain cookie you need to use nginx to do a reverse proxy.

Guess you like

Origin www.cnblogs.com/suyang-java/p/11497052.html