Java study notes-Day55 session tracking



1. Overview of Session Tracking


For web applications, a session is a continuous communication process between the browser and the server.

The HTTP protocol is stateless, that is, after a request is completed, the HTTP protocol no longer records related information.

Session tracking technology can track the interaction between the client and the server, save and memorize related information, and save the requested state information. Session tracking can save state information and solve the drawbacks of the stateless nature of the HTTP protocol

Two, commonly used session tracking technology


There are four commonly used session tracking techniques:

(1) URL method: the information that needs to be saved is directly appended to the URL, for example:http://127.0.0.1:8080/BlogSytem/Servlet.do?username=tom&pwd=123456

(2) Hidden field method: You can use the hidden field in the form to save relevant information, for example:

	 <input type="hidden" name=“status" value=“true">

(3) Cookie method: Save the status information to the client, and the server can obtain relevant information for analysis, thereby generating a response to the client; for example, simplifying the login function can be achieved by using cookies.

(4) Session mode: Save the state information to the server's session object, and bind it to the client through a uniquely marked ID value; for example, the access control function can be implemented using Session.

For example, store user login data: ① Session (stored on the server) ② Cookie (stored on the client)

Three, Cookie and Session

1、Cookie


A cookie is a small text saved on the client; it can be used to save the status information during the user's activity to the client. The server can obtain the information for processing and track the status of the user.

Different browsers have different viewing methods. Take the Chrome browser as an example, the way to view the cookies of the current page: Settings——>Privacy and Security of Settings——>Cookies and other website data——>Check all cookies and website data, you can see all cookies information. You can also check the cookies of the current website through F12——>Application——>cookies.

Cookie contains a series of attributes:

  • name: The name of the cookie, each cookie has a name.
  • content: The value of the cookie, which exists as a key-value pair together with the name.
  • domain: domain, the domain name of the cookie, such as 163.com in the picture on the left, indicating that the current cookie is from 163.com.
  • path: Path. When accessing the path under 163.com, the current cookie will be sent.
  • created: the time when the cookie was created.
  • Expired: The time when the cookie expires.
  • Maximum life time: The time difference between the expiration time and the creation time is the maximum life time of the cookie. After this time, the cookie will expire and will no longer be sent to the corresponding domain address.

The Cookie class (javax.servlet.http.Cookie) is defined in the Servlet specification. When an object of this class is created, a Cookie can be created, and the method can be called to set attributes for the Cookie.

Method declaration Method description
Cookie(java.lang.String name, java.lang.String value) Create a Cookie object, specify the name and corresponding value;
void setMaxAge(int expiry) Set the maximum life time (seconds), if not set, the current browser is closed and the cookie becomes invalid;
void setValue(java.lang.String newValue) Set the value of Cookie;
setDomain(java.lang.String domain) Set the domain name of the cookie;

To save the Cookie to the client, it is necessary to add it to the response object. The method of setting Cookie is defined in the response interface:

Method declaration Method description
void addCookie(Cookie cookie) Save the Cookie object to the corresponding response object;
	Cookie cookie1 = new Cookie("username", user.getUname());
	Cookie cookie2 = new Cookie("pwd", user.getUpwd());
	cookie1.setMaxAge(60 * 60 * 24);
	cookie2.setMaxAge(60 * 60 * 24);
	response.addCookie(cookie1);
	response.addCookie(cookie2);

When visiting the same domain and path, cookies that have not expired will be automatically sent to the website through the request. The request interface in the Servlet specification defines the method to obtain the Cookie object:

Method declaration Method description
Cookie[] getCookies() Get all Cookie objects in the request and return an array;
	<%
		String username = "";
		String userpwd = "";
		Cookie[] cookies = request.getCookies();
		for (Cookie ck : cookies) {
			if (ck.getName().equals("username")) {
				username = ck.getValue();
			}
			if (ck.getName().equals("pwd")) {
				userpwd = ck.getValue();
			}
		}
	%>

2、Session


Session is an object stored on the server, which is created and maintained by the server. The server creates and maintains a Session object for each session between the client and the server. Each server differs in the underlying implementation of Session creation and maintenance.

Tomcat uses Cookie to maintain the ID value of the Session object. The name of the Cookie is JSESSIONID.

Each Session object has a unique ID value, which is stored in the Cookie named JSESSIONID.

When the client starts a session process, take Tomcat as an example, the steps are shown in the figure:
Insert picture description here
HttpSession interface is defined in the Servlet specification to implement Session technology. To use HttpSession, you must first obtain its object. The method to obtain the HttpSession object is defined in the request interface:

Method declaration Method description
HttpSession getSession() Get the Session object related to the current request, if it does not exist, create a new one;
HttpSession getSession(boolean create) If create is true, it is the same as the getSession() method; if create is false, if it does not exist, it returns null;
	HttpSession session = request.getSession();

With session attributes, objects can be shared within the scope of the session. Similar to the request attributes learned earlier, the session can also add, modify, and delete attributes. HttpSession interface provides methods related to attributes:

Method declaration Method description
void setAttribute(java.lang.String name, java.lang.Object o) Set any type of object as an attribute of the session and specify a name;
java.lang.Object getAttribute(java.lang.String name) Get the value of the attribute through the name of the attribute;
void removeAttribute(java.lang.String name) Delete the attribute by the name of the attribute;
	HttpSession session = request.getSession();
	session.setAttribute("user", user);

Reasons for Session failure: Session objects are objects stored on the server side, and there are always some server resources that need to be occupied. Some data of the user is often stored in the session. If it is always valid, there is a certain security risk.

Session invalidation method: The server has a default session invalidation time. Tomcat defaults to 30 minutes; the
invalidation time can be configured in web.xml, in minutes.

	<session-config>
	  <session-timeout>50</session-timeout>
	</session-config>

Calling two methods in the HttpSession interface can destroy the specified session object.

Method declaration Method description
void setMaxInactiveInterval(int interval) Set the inactivity time for a specific session object. If it is not accessed and used within this time, the container will automatically destroy the session object;
void invalidate() Immediately destroy the session object that calls this method, and unbind all objects bound to the session;

Four, use Ajax to get data


The data transmitted by the back end is in Json format. The main tools are gson (java class library), fastjson (Ali), jackson (frame use, multiple jar packages).

Implementation steps:

1. Backend
① Put gson.jar in the lib directory under WEB-INF under WebContent.
② Set the response format. response.setContentType("application/json;charset=utf-8");
Gson gson = new Gson(); String str = gson.toJson(list);
PrintWriter out = response.getWriter(); out.print(str);

2. The front end
<script src="js/jquery-2.0.3.js" type="text/javascript" charset="utf-8"></script>
$.get("url地址", function(res) { 代码 });
③ Traverse and process the results.

Note: The ${v.userid}default is the template string in ECMAscript6 in the html page, and the EL expression in the JSP page. In JSP pages, EL expressions also use the $ symbol to insert variables, so the use of the $ symbol in the template string will cause conflicts and will not be recognized. The template string used in Ajax ${v.userid}will be parsed into an empty string by JSP. Therefore, the template string must ${}be escaped in JSP , preceded by a slash \${}, to distinguish it from EL expressions.

  • AjaxServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 javax.servlet.http.HttpSession;

import com.etc.bs.entity.User;
import com.etc.bs.service.UserService;
import com.google.gson.Gson;

/**
 * Servlet implementation class AjaxServlet
 */
@WebServlet("/AjaxServlet.do")
public class AjaxServlet extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;

	private UserService userservice = new UserService();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AjaxServlet() {
    
    
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		request.setCharacterEncoding("utf-8");
		String op = "";
		if (request.getParameter("op") != null) {
    
    
			op = request.getParameter("op");
		}

		if ("login".equals(op)) {
    
    
			doLogin(request, response);
		} else {
    
    
			doQuery(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		doGet(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		// 设置响应格式
		response.setContentType("application/json;charset=utf-8");
		String keywords = "";
		if (request.getParameter("keywords") != null) {
    
    
			keywords = request.getParameter("keywords");
		}
		// keyword赋值为""
		List<User> list = userservice.getUserByName(keywords);
		// 创建Gson对象
		Gson gson = new Gson();
		// 将list转换成json格式的字符串
		String str = gson.toJson(list);
		PrintWriter out = response.getWriter();
		out.print(str);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
    
    
		
	}

}

  • ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<style type="text/css">
td {
     
     
	border: 1px solid black;
}

#tab {
     
     
	width: 600px;
	text-align: center;
}
</style>
</head>
<body>
	<button type="button" id="btn">获取数据</button>
	<div id="div1">
		<table id="tab" border="1" cellspacing="0" cellpadding="20">
			<tr>
				<th>编号</th>
				<th>名字</th>
				<th>密码</th>
				<th>年龄</th>
				<th>性别</th>
				<th>操作</th>
			</tr>
		</table>
	</div>

	<script src="js/jquery-2.0.3.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
			$(function() {
     
     
				//按钮的单击事件
				$("#btn").click(function() {
     
     
					//$(selector).get(url,data,success(response,status,xhr),dataType)
					//参数 url地址,参数回调函数
					$("#tab").html(`<tr>
							<th>编号</th>
							<th>名字</th>
							<th>密码</th>
							<th>年龄</th>
							<th>性别</th>
							<th>操作</th>
						</tr>
					`);
					$.get("http://127.0.0.1:8080/BlogSystem/AjaxServlet.do", function(res) {
     
     
						$.each(res, function(index, v) {
     
     		
							//遍历一次就加一行数据
							$("#tab").append(`<tr>
								<td>${
       
       v.userid}</td>
								<td>${
       
       v.uname}</td>
								<td>${
       
       v.upwd}</td>
								<td>${
       
       v.uage}</td>
								<td>${
       
       v.usex}</td>
								<td><input type="button" class="btndel" value="删除"></td>
								</tr><br/>`
							);
						});
					});
				});
			});
		</script>
	<script type="text/javascript">
			$(function () {
     
     
				$(document).on("click",".btndel",function () {
     
     
					console.log($(this).parents("tr").children("td:eq(0)").text())
					$(this).parents("tr").remove();
				});
				
			});
		</script>

</body>
</html>

Guess you like

Origin blog.csdn.net/qq_42141141/article/details/111659107