当前位置:网站首页>Cookies and sessions

Cookies and sessions

2022-06-12 11:53:00 Bewitch one

Cookie and Session

conversation

conversation : The user opens a browser , Click a lot of hyperlinks , Visit multiple Web resources , Close the browser , This process is called conversation .

Stateful conversation : A server proves that the client has come ?

  1. The server sends a letter to the client , The next time the client accesses the server, just bring the letter ;cookie
  2. The server registers that you've been here , Next time you come, I'll match you .session

Two techniques for saving a session

  1. cookie
  • Client technology ( The corresponding , request )
  1. session
  • Server technology , Using this technology , Can save user session information . We put information and data in Session in .

Common scenes : After logging into the website , No need to log in repeatedly .

Cookie

  1. Get... From the request cookie Information
  2. The server corresponding to the client cookie
package com.guhuo.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        //  The server , Tell you , When you came , Encapsulate this time into a letter , You bring it next time , I knew when you came 

        //  Solve the Chinese garbled code 
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");

        PrintWriter out = resp.getWriter();

        // Cookie, Get from the server and the client 
        Cookie[] cookies = req.getCookies(); // Here we return an array , Explain that there may be more than one Cookies

        //  Judge Cookie Whether there is 
        if (cookies != null) {
    
            //  If there is ?
            out.write(" The time of your last visit was :");

            for (int i = 0; i < cookies.length; i++) {
    
                Cookie cookie = cookies[i];
                //  obtain cookie Name 
                String name = cookie.getName();
                if(name.equals("lastLoginTime")){
    
                    // obtain cookie Value 
                    String value = cookie.getValue();
                    long lastLoginTime = Long.parseLong(value);
                    Date data = new Date(lastLoginTime);
                    out.write(data.toLocaleString());
                }
            }
        } else {
    
            out.write(" This is your first visit to this website "); //  When I first visited the website , No, Cookie
        }
        //  The service gives the client a corresponding cookie:
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        cookie.setMaxAge(24*60*60); //  Valid for 1 God 

        resp.addCookie(cookie);
    }

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

cookie: It is usually saved in the local user directory appdata Next .

  • One cookie Only one message can be saved
  • One web Sites can send multiple cookie, At most 20 individual cookie
  • Cookie There's a limit to the size 4kb
  • 300 individual cookie Browser limit

Delete cookie:

  • Do not set the validity period , Close the browser , Automatic failure ;
  • Set the validity period to 0;

Session

What is? Session:

  • The server will give each user ( browser ) Create a Session object
  • One Session Monopolize a browser , As long as the browser is not closed , This Session There is a
  • After the user logs in , It can access the whole website

Session and Cookie The difference between

  • Cookie It is to write the user's data to the user's browser , Browser save ( You can save multiple )
  • Session Write the user's data to the user's exclusive Session in , Server side save ( Keep important information , Reduce the waste of server resources )
  • Session Objects are created by the server

Use scenarios :

  • Save the information of a login user ;
  • Shopping cart information ;
  • Data often used throughout the website , We keep it in Session in ;

Session Use

package com.guhuo.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemo extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        //  Solve the mess 
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //  obtain Session
        HttpSession session = req.getSession();

        //  to Session There's something in it 
// session.setAttribute("name", "guhuo");
        session.setAttribute("name", new Preson("guhuo", 1));
        //  obtain Session Of ID
        String sessionId = session.getId();

        //  Judge Session Is it created 
        if(session.isNew()) {
    
            resp.getWriter().write("session Create success ,ID:" + sessionId);
        } else {
    
            resp.getWriter().write("session And exist in the server ,ID:" + sessionId);
        }

        //  Cancellation session
        session.removeAttribute("name");
        session.invalidate();
    }

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

}

Session expires automatically , Can be found in web.xml Set in :
 Insert picture description here

原网站

版权声明
本文为[Bewitch one]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121144502932.html