Servlet session tracking basics


foreword

提示:这里可以添加本文要记录的大概内容:

In web applications, session tracking is a technique that maintains a persistent connection between a client and a server in order to track user activity between different pages.

Servlet session tracking can be implemented in the following ways:

  1. Cookies: Servlets can store a unique identifier in a client-side cookie to track user sessions with each request.

  2. URL rewriting: Servlets can add unique identifiers to URLs to track user sessions with each request.

  3. Hidden form fields: Servlets can add unique identifiers to form fields to track user sessions with each request.

  4. HttpSession object: Servlet can use HttpSession object to maintain user session state on the server side. Each session object has a unique identifier that allows user sessions to be tracked on the server side.


提示:以下是本篇文章正文内容,下面案例可供参考

Cookie instance

Prepare to send cookies to the front end:

import java.io.IOException;
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;
@WebServlet("/cookie1")
public class SendCookieToClientServlet extends HttpServlet{
    
    
	//动态项目      没有去 其他下找 web
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		System.out.println("准备发送cookie给客户端");
		Cookie cookie = new Cookie("login", "zhangsan");
		cookie.setMaxAge(60*60*24*7);  //单位是:秒,这里是7天
		resp.addCookie(cookie);
		
	}
}

Run the project:
insert image description here
It means that the code is effective, and the cookie is sent to the client

Get the client's cookie:

import java.io.IOException;
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;

@WebServlet("/cookie2")
public class ReciveCookieFromClinetServlet extends HttpServlet{
    
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		System.out.println("获取客户端的cookie");
		Cookie cookiesCookie [] = req.getCookies();
		for (int i = 0; i < cookiesCookie.length; i++) {
    
    
			Cookie cookie = cookiesCookie[i];
			System.out.println(cookie.getName()+"-"+cookie.getValue());
		}
	}
}

Restart the server, clear the console, and run the webpage to link
insert image description here
Cookie technology core : when visiting for the first time, the server sends some cookie information and saves it to the client, within the validity period, when the same client sends another request to the server, the cookie will be sent to the server by default

Cookie Disadvantages

Low security
Compatibility issues
Timeliness issues
Storage capacity limitations

Cookie case code

[Example 1: Store cookie from Servlet to client]

//SetCookie Servlet
Cookie c=new Cookie("season","spring");
c.setMaxAge(30);
response.addCookie(c);
Cookie d=new Cookie("nextseason","summer");
d.setMaxAge(10);
response.addCookie(d);

[Example 2: Read cookie on the client side]

//getCookie.jsp
<%
Cookie[] a=request.getCookies();
for(int i=0;i<a.length;i++)
{
    
    
out.println(a[i].getName()+:"+a[i].getValue()+"<br>");
}
%>

[Example 3: Using cookie counting]

//visitCount.jsp计数次数
<%@ page contentType="text/html;charset=UTF-8" %>
<%int count = 0; 
 Cookie[] cookies = request.getCookies(); / / 得到所有的Cookie
if(cookies != null) {
    
     
   for(int i=0; i<cookies.length; i++) {
    
    
       if(cookies[i].getName().equals("Counter"))
            count = Integer.parseInt(cookies[i].getValue());  //获取Counter以前值
   }  }
count++;
if(count == 1)
   out.println("欢迎首次光临");
else 
  out.println("您已经光临了" + count+"次");
// 将新的count写入客户端
Cookie c = new Cookie("Counter", ""+count);
c.setMaxAge(60*60*24*365);       // Cookie 的有效期为 1 年
response.addCookie(c); %>

[Example 4: Delete cookie]

//cookie remove.jsp
<%
int count=0;
// 将新的count写入客户端
Cookie c = new Cookie("Counter", ""+count);
c.setMaxAge(0);       // Cookie 的有效期为 0
response.addCookie(c); %>

[Example 5: Shopping cart login experiment, 1. Enter the shopping cart page from the home page]

//首页home.html
<a href="cart.jsp">购物车</a>
<a href=”remove.jsp”>删除计数cookie</a>

[Example 5: Shopping cart login experiment, 2. On the shopping cart page, first determine whether the user has logged in, otherwise jump to the login page login.html]

//购物车  cart.jsp
<h1>购物车</h1>
<%int count = 0; 
 Cookie[] cookies = request.getCookies(); // 得到所有的Cookie
if(cookies != null) {
    
     
   for(int i=0; i<cookies.length; i++) {
    
    
       if(cookies[i].getName().equals("Counter"))
            count = Integer.parseInt(cookies[i].getValue());  //获取Counter以前值
   }  }
 
if(count==0)response.sendRedirect(request.getContextPath()+"/login.html");
%>
//login.html
<h1>用户登录</h1>
	<form action="visit.jsp" method="post">
		用户名<input type="text" name="user"><br><br>
		密码
		<input type="password" name="password"><br>		
		<input type="submit" value="提交">
	</form>
//visit.jsp
<%int count = 0; 
 Cookie[] cookies = request.getCookies(); // 得到所有的Cookie
if(cookies != null) {
    
     
   for(int i=0; i<cookies.length; i++) {
    
    
       if(cookies[i].getName().equals("Counter"))
            count = Integer.parseInt(cookies[i].getValue());  //获取Counter以前值
   }  }
 
count++;
if(count == 1)
  response.getWriter().println("欢迎首次光临");
else 
  response.getWriter().println("您已经光临了" + count+"次");
 
// 将新的count写入客户端
Cookie c = new Cookie("Counter", ""+count);
c.setMaxAge(60*60*24*365);       // Cookie 的有效期为 1 年
response.addCookie(c); 
response.sendRedirect(request.getContextPath()+"/cart.jsp");
%>

Session

Use Session to maintain the login status of a session:

  1. When the first request is made, a Session object is created on the server side, and a sessionId is generated for this object.
  2. At the same time, use Cookie to return this sessionId to the client and store it in the client's Cookie.
  3. When the client initiates the next request, it must carry this sessionId and send it to the server.
  4. According to the received sessionId, the server can retrieve the Session object, thus obtaining the information of the last request.

Create StoreDataServlet class: used to store a User object (representing user information) in HttpSession.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.org.apache.bcel.internal.generic.NEW;
import po.User;
@WebServlet("/store")
public class StoreDataServlet extends HttpServlet{
    
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		HttpSession session = req.getSession();
		session.setAttribute("login", new User(1,"二哈喇子","吃饭快"));
	
	}
}

Create User class: Represent user entity, including user ID, user name and role.

public class User {
    
    
	private Integer id;
	private String name;
	private String role;
	public User() {
    
    
		super();
		// TODO 自动生成的构造函数存根
	}
	public User(Integer id, String name, String role) {
    
    
		super();
		this.id = id;
		this.name = name;
		this.role = role;
	}
	@Override
	public String toString() {
    
    
		return "User [id=" + id + ", name=" + name + ", role=" + role + "]";
	}
	
}

Create the GetDateServlet class: used to read the stored User object from the HttpSession and output it to the console.

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

@WebServlet("/get")
public class GetDateServlet extends HttpServlet{
    
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		HttpSession session = req.getSession();
		System.err.println(session.getAttribute("login"));
		
	}
}

This web application implements the session management function based on the Servlet API, that is, stores and manages user session information on the server side. When a user logs in, their user information will be stored in the HttpSession object, and then during the user session, this information can be accessed and used by other Servlet classes or JSP pages. Through session management technology, Web applications can manage and control user status more conveniently, improving the security and reliability of applications.

Restart the server, clear the console, run the link store on the webpage,
insert image description here
and run the get path to take it out
insert image description here

Session creation and destruction

Session creation

Call request.getSession()method to get this Session object

  1. No parameters: getSession()If there is a Session object, return some, if not, let the server create a new Session object.
  2. With parameters: pass a Boolean type with parameters, if it is true, it will have the same effect as without parameters; if it is false, if the Session object cannot be found, a new one will not be created, and null will be returned

A session will not be created without calling the getSession method.

Session destruction

There are only two situations for the destruction of the Session:
First: the session calls the session.invalidate() method.
Second: The two requests before and after exceeded the life cycle time specified by the session.

By default, it will be destroyed in 15 minutes, and it can also be destroyed actively

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//单词多个r
@WebServlet("/destroy")
public class DestroySessionServlet extends HttpServlet{
    
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		HttpSession session = req.getSession();
		session.invalidate();
	}
}

Restart the server, clear the console, run the links in sequence on the web page,
insert image description here
insert image description here
and then run destroy to destroy

Finally, run get to get
insert image description here
the timeout destruction:
Please add a picture description

    <session-config>
    	<session-timeout>30</session-timeout>
    </session-config>

Delete the code after the timeout destruction test

The difference between Session and Cookie

1. Cookies can be stored in the browser or locally. Sessions can only exist on the server.
2. Sessions can store any java object. Cookies can only store objects of String type
. It is related to the memory size of the server
.

different

Storage location: The cookie is stored in the hard disk of the client, which belongs to offline storage, and the session is stored in the memory of the server.

Survival time: The cookie can be stored on the client for a long time. The specific survival time is determined by the value specified by the setMaxAge() method. The session is generated when the user accesses the server, and disappears when the client times out or goes offline.

Security: Cookies are stored on the client side and may be read by websites with ulterior motives. The security is poor, while the session is stored in the memory of the server, which cannot be modified by the user and disappears when the client browser is closed. The security is better.

connect

Whether it is a cookie or a session hidden object, the browser needs to support cookies and cookies are not disabled.

Although the Session is stored in the server-side memory, the client's browser needs to identify itself through the Session ID in the cookie, and bind the ID to the Session on the server, so as to realize the session state management between the client and the server.
Therefore, Session and Cookie are actually related to each other, and the two are usually used together.

Guess you like

Origin blog.csdn.net/rej177/article/details/131752692