Java web—Cookie and Session object

Then the Servlet summary of the previous article.

Introduction:
1. What is a conversation ?

  • From opening the browser, to accessing the page, to closing the browser, the whole process is a session

2. The characteristics of the session ?

  • A session may contain multiple requests
  • A complete session is only for one user

3. Session management technology :

  • Cookie technology: client technology
  • Session technology: server technology

This blog will summarize the use of Cookie and Session


1. Cookie technology: client technology

1. What is a cookie ?

  • Cookie is one of the specifications of the HTTP protocol, it is the small data transmitted between the server and the client.
  • Cookie is the data that the server saves on the client side! (Similar to a membership card, saved in the user's hands (client))
  • Cookie is a key-value pair!

2. Common uses of cookies :

  • The site tracks the number of visits by a particular visitor, the time of the last visit and the visitor’s path to the site;
  • Help the site to count user personal information to achieve a variety of personalized services.
  • Realize automatic login function

3. The implementation principle of Cookie :

  • The first time you visit the server, the server will increase the Set-Cookie header field, send the cookie information to the browser, and save it on the client.
  • When subsequently accessing the server, the user information will be sent to the server in the form of a cookie in the request message, so that the server can distinguish which user is making the current request.

类 javax.servlet.http.Cookie 表示cookie

Method of obtaining cookie information:

getName()名称, 
getValue(), 
getPath()cookie所在的目录, 
getDomain()有效域 
getMaxAge()有效时间, 
getSecure()只能使用安全的协议

Method of setting cookie information:

setValue(), 
setPath(), 
setDomain(), 
setMaxAge()设置在客户端硬盘上保存的最大时间,单位为秒

Get cookies from the request:

 Cookie[] HttpServletRequest.getCookies( ) 

Add cookies to the response:

HttpServletResponse.addCookie("name","value")

4. Write Cookie to the client :

1. Create Cookie

Cookie c=new Cookie("name", "value");

2. Set the properties of the Cookie

c.setMaxAge(60*60*24); 
c.setDomain("pdsu.edu.cn")
c.setPath("/")

3. Call the addCookie method of response to write it to the client

response.addCookie(c)

5. Steps to read Cookie :

Read all cookies that can be read by this server from the client:

Cookie[] cookies=request.getCookies();

Find out the cookies you need:

for(int i=0;i<cookies.length;i++) {
    
    
if( cookies[i].getName().equals(“wanted”) ){
    
    
      ......
   }
}

Example :
Use the Cookie object to realize the welcome message. When the user visits the application for the first time, the welcome message is displayed, and the first visit is prompted, and so on.

code show as below:

package cn.servlet;

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

public class IndexServlet extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		response.setContentType("text/html;charset=utf-8");
		Cookie[] cookies = request.getCookies();
		Integer integer = 0;
		if (cookies != null) {
    
    
			for (int i = 0; i < cookies.length; i++) {
    
    
				if ("A".equals(cookies[i].getName())) {
    
    
					integer = Integer.parseInt(cookies[i].getValue());
				}
			}
		}
		integer++;
		Cookie cookie = new Cookie("A", integer + "");
		if (integer <= 1) {
    
    
			response.getWriter().append("欢迎A").append("首次访问本网站");
		} else {
    
    
			response.getWriter().append("欢迎A第").append(integer + "").append("次访问本网站");
		}
		cookie.setMaxAge(10);
		response.addCookie(cookie);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		doGet(request, response);
	}

}

2. Session technology: server technology

1. What is Session technology ?

  • A session management technology that saves the data in the session to the server.
  • It is implemented based on session-level cookies.
  • The popular session technology is like the medical card issued by the hospital to the patient and the process in which the hospital keeps the case file for each patient. When a patient goes to the hospital, he only needs to show the medical card, and the doctor can check the patient's medical information according to the card number.
  • When the browser accesses the server, the Servlet container creates a Session object and ID attribute. Among them, the Session object is equivalent to the medical record file, and the ID is equivalent to the medical card number. During subsequent visits, as long as the identification number is passed to the server, it is It can be judged which client sent it, and then select the corresponding Session object for its service. In general, Session uses Cookie technology to transfer ID attributes.

2. Session implementation principle :

Illustration:
Insert picture description here


  • The data in the session can be shared by a user in a session.

  • Everyone's session is different.
    Insert picture description here


  • Retrieval and creation of session_id:
    Insert picture description here

3. Session session :

1. What is session tracking technology?

  • HTTP is a stateless protocol, that is, a protocol without memory, and data cannot be shared between each request. This makes it impossible to know when the session starts and ends, and it is impossible to determine the identity of the user who made the request. This shows that you need to use additional means to track the session!
  • Sharing data in a session is session tracking technology

2. The session tracking process can be divided into:
Insert picture description here
3. The commonly used session tracking mechanisms are:

  1. Cookies
    characteristics: the most commonly used
    Principle: the engine saves the user session ID in a cookie, saves it to the client, and sends this cookie to the server in future requests

  2. URL Rewriting
    Features: Lowest performance.
    Usage: When the client cannot accept cookies.
    Principle: Write the session id into the URL. Such a URL will be parsed by the engine and associated with a session.
    Example:http://www.myser.com/catalog/index.htm;jsessionid=1234

  3. Form hiding
    Principle: Use the hidden attribute in HTML to secretly transmit the client information to the server along with the request without the user's awareness.
    Use:
    <input type="hidden" name="userID" value="15">
    Advantages: When the session data is transmitted to the server, it will not be transmitted. The session data is exposed on the URL.
    Disadvantage: When the user directly views the HTML source file, the session data will be exposed.

4. Comparison of session tracking mechanism:

Insert picture description here
5. Session management mechanism:

  1. Create a session:
  • HttpServletRequestThe getSession( )method returns the current session if the session is not creating a new session
  • getSession(true) Perform the same function as above.
  • getSession(false)Visit an existing session instead of creating a new one, and return null if there is no valid session

Example:

  HttpSession session=request.getSession(true)
  1. Store and access session attributes:
  • Standard session attributes include: session identifier, data, creation time, last access time, etc., all “名-值”对stored in the form
  • HttpSession provides a standard way to store objects in memory and extract these objects from subsequent requests by the same user
  • How to save data in a session:setAttribute(String s, Object o)
  • The method to extract the original saved object from the session: getAttribute(String s)
  1. Close the session:

1. Explicitly close:HttpSession.invalidate( )

2. Implicit closure-session timeout (waiting for timeout automatic operation)

  • The default timeout interval is 1800 seconds
  • Before invalidation, you can use the setInactiveInterval(int seconds) method to control this time interval between client requests.
  • Set a negative value to ensure that the session will never time out

4. Common methods of Session :

getAttribute()从session中获取以前存储的值
setAttribute()将键与值关联起来,存储进session
removeAttribute()删除session中存储的对应键的值
invalidate()删除整个session及其存储的键值
logout()注销当前用户
getId()获取每个session对应的唯一ID
getCreationTime()获取session创建的时间
getLastAccessedTime()获取session最后被访问的时间
getMaxInactiveInterval()在用户没有访问的情况下,会话在被自动废弃之前应该保持多长时间
getAttributeNames()返回session中所有属性的名称

5. Session listener:

Role: monitor the actions (creation, destruction, etc.) and status of the object

  • New session object created
  • Destroy the session object

To achieve the session listener, you need to implement javax.servlet.http.HttpSessionListeneran interface

Guess you like

Origin blog.csdn.net/qq_43531669/article/details/105569716