当前位置:网站首页>Detailed explanation of cookies and sessions

Detailed explanation of cookies and sessions

2022-06-26 16:07:00 Hua Weiyun

Conversational Technology

conversation : A session contains multiple requests and responses .

  • One session : The first time a browser sends a request to a server resource , Session creation , Until one side is disconnected
    function : Between multiple requests within the scope of a session , Shared data
    The way :
  • Client session technology :Cookie
  • Server side session technology :Session

Cookie

Concept

Client session technology , Save data to client

Quick start

Use steps :

  1. establish Cookie object , Data binding
    new Cookie(String name, String value)
  2. send out Cookie object
    response.addCookie(Cookie cookie)
  3. obtain Cookie, Get the data
    Cookie[]  request.getCookies()

Realization principle

Based on the response header set-cookie And the request header cookie Realization

cookie The details of the

  1. Can I send more than one at a time cookie?
    You can create multiple Cookie object , Use response Call several times addCookie Method to send cookie that will do .
  2. cookie How long to save in the browser ?
  • By default , When the browser is closed ,Cookie The data is destroyed
  • Persistent storage :
    setMaxAge(int seconds)
  • Positive numbers : take Cookie The data is written to a file on the hard disk . Persistent storage . And designate cookie Survival time , After the time ,cookie The file is automatically invalidated
  • negative : The default value is
  • zero : Delete cookie Information
  1. cookie Can you save Chinese ?
    stay tomcat 8 Before cookie Can't store Chinese data directly in .
  • Need to transcode Chinese data — It is generally used URL code (%E3)
    stay tomcat 8 after ,cookie Support Chinese data . Special characters are still not supported , It is recommended to use URL Encoding storage ,URL Decoding and parsing
  1. cookie Sharing issues ?
  2. Suppose it's in a tomcat Server , Deployed multiple web project , So in these web In the project cookie Can we share ?
  • By default cookie Cannot share
  • setPath(String path): Set up cookie The scope of acquisition . By default , Set the current virtual directory
    • If you want to share , Then you can put path Set to "/"
  1. Different tomcat Server room cookie Sharing issues ?
    setDomain(String path): If the primary domain name is the same , So many servers cookie Can be Shared
    setDomain(".baidu.com"), that tieba.baidu.com and news.baidu.com in cookie Can be Shared

Cookie The characteristics and functions of

  1. cookie Store data in the client browser
  2. Browser for single cookie There is a limit to the size of (4kb) as well as For the total under the same domain name cookie There is also a limit to the number (20 individual )

effect :

  1. cookie Generally used to store a small amount of less sensitive data
  2. Without logging in , Complete the identification of the client by the server

Case study : Remember the last time you visited

demand

  1. Visit one Servlet, If it's a first visit , Prompt : Hello! , Welcome to .
  2. If it's not my first visit , Prompt : welcome back , Your last visit was : Display time string

analysis

  1. May adopt Cookie To complete
  2. On the server Servlet Determine if there is a name lastTime Of cookie
  • Yes : Not for the first time
    • The response data : welcome back , Your last visit was :2022 year 5 month 1 Japan 08:08:08
    • Write back to Cookie:lastTime=2022 year 5 month 1 Japan 08:08:08
  • No, : It's my first visit to
    • The response data : Hello! , Welcome to
    • Write back to Cookie:lastTime=2022 year 5 month 1 Japan 08:08:08

Code implementation

package cn.zjq.cookie;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;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.net.URLDecoder;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Date;@WebServlet("/cookieTest")public class CookieTest extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	// Set the data format and encoding of the message body of the response 	response.setContentType("text/html;charset=utf-8");	//1. Get all Cookie	Cookie[] cookies = request.getCookies();	boolean flag = false;// No, cookie by lastTime	//2. Traverse cookie Array 	if(cookies != null && cookies.length > 0){		for (Cookie cookie : cookies) {			//3. obtain cookie The name of 			String name = cookie.getName();			//4. Determine if the name is :lastTime			if("lastTime".equals(name)){				// There is a reason Cookie, Not for the first time 				flag = true;// Yes lastTime Of cookie				// Set up Cookie Of value				// Get the string of the current time , To reset Cookie Value , To resend cookie				Date date  = new Date();				SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan  HH:mm:ss");				String str_date = sdf.format(date);				System.out.println(" Before coding :"+str_date);				//URL code 				str_date = URLEncoder.encode(str_date,"utf-8");				System.out.println(" After the coding :"+str_date);				cookie.setValue(str_date);				// Set up cookie Life time of 				cookie.setMaxAge(60 * 60 * 24 * 30);// A month 				response.addCookie(cookie);				// The response data 				// obtain Cookie Of value, Time 				String value = cookie.getValue();				System.out.println(" Before decoding :"+value);				//URL decode :				value = URLDecoder.decode(value,"utf-8");				System.out.println(" After decoding :"+value);				response.getWriter().write("<h1> welcome back , Your last visit was :"+value+"</h1>");				break;			}		}	}	if(cookies == null || cookies.length == 0 || flag == false){		// No, , First visit 		// Set up Cookie Of value		// Get the string of the current time , To reset Cookie Value , To resend cookie		Date date  = new Date();		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd Japan  HH:mm:ss");		String str_date = sdf.format(date);		System.out.println(" Before coding :"+str_date);		//URL code 		str_date = URLEncoder.encode(str_date,"utf-8");		System.out.println(" After the coding :"+str_date);		Cookie cookie = new Cookie("lastTime",str_date);		// Set up cookie Life time of 		cookie.setMaxAge(60 * 60 * 24 * 30);// A month 		response.addCookie(cookie);		response.getWriter().write("<h1> Hello! , Welcome to </h1>");	}}	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		this.doPost(request, response);	}}

Session

Concept

Server side session technology , Sharing data among multiple requests in a session , Save the data in the object on the server side .HttpSession

Quick start

  1. obtain HttpSession object :
    HttpSession session = request.getSession();
  2. Use HttpSession object :
    Object getAttribute(String name)
    void setAttribute(String name, Object value)
    void removeAttribute(String name)

principle

Session The realization of depends on Cookie Of .

details

  1. When the client is shut down , The server does not shut down , Get twice session Is it the same ?
    By default . No .
    If you need the same , You can create Cookie, The key is JSESSIONID, Set the maximum lifetime , Give Way cookie Persistent save .
Cookie c = new Cookie("JSESSIONID",session.getId());c.setMaxAge(60*60);response.addCookie(c);
  1. The client does not shut down , After the server is shut down , Acquired twice session Is it the same ?
    Not the same , But make sure the data is not lost .tomcat Automatically complete the following work
  • session Passivation of :
    • Before the server is shut down properly , take session Serialize objects to hard disk
  • session Activation of :
    • After the server starts , take session The file is converted to... In memory session Object can .
  1. session When it was destroyed ?
  • Server down
  • session Object call invalidate() .
  • session Default expiration time 30 minute
    Optional configuration modification
<session-config>	<session-timeout>30</session-timeout></session-config>

Session Characteristics

  1. Session Data used to store multiple requests for a session , There is a server side .
  2. Session Can store any type , Data of any size .

Session And Cookie The difference between

  1. Session Store data on the server side ,Cookie On the client side
  2. Session There is no data size limit ,Cookie Yes
  3. Session Data security ,Cookie Relative to insecurity
原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261550115124.html