Servlet(4)

1. Why do you need session tracking?
Insert picture description here

Use the http request sent by the browser. The http request uses the http protocol, and the http protocol is a stateless protocol. It will not actively record who the user using the http protocol is. Once the request is sent successfully, the server will make After the response, the link between the browser and the server will disappear at this time, and the server does not know where the request comes from and who sent it. So at this time we need to record/save the status of the request/link. The process of realizing this record/save request/link status is called session tracking.
2. What is session tracking?
The process by which the server handler realizes the recording/saving of the request/link status is called session tracking.
3. What are the four session tracking technologies, and their respective advantages and disadvantages?
1. URL rewriting: rewrite the id information of the user Session into the URL address to identify different users on the server side.
https://blog.csdn.net/qq_33098039/article/details/78184535?sessionid=123456
URL rewriting can still work when the client disables cookies or does not support cookies .
2. Hide the form field: add the ID information of the user's session to the HTML form element **** and submit it to the server. This form element is not displayed on the client side and cannot be seen when browsing. It is included in the source code.
3. Cookie: A cookie is a small piece of information sent by the Web server to the client. When the client requests it, the information can be read and sent to the server for user identification. The server is created and saved on the browser side, cannot cross domain names, and is limited in size and quantity.The client can save this Cookie object in two ways. One method is to save it in the client's memory, called a temporary cookie, which will disappear after the browser is closed. Another way is to save it on the client's disk, called a permanent cookie. In the future, as long as the client visits the website, the cookie will be sent to the server again, provided that the cookie is within the validity period. In this way, the tracking of customers is realized . Cookies can be banned .
4. Session: Every user has a different session, which cannot be shared between users. It is exclusive to each user. Information can be stored in the session. Save it on the server side. Need to solve the problem of sharing among multiple servers. If the content of the Session is too complex, it may cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as concise as possible.
Session relies on Cookie. If Cookie is disabled, session will also be invalid.
When the user sends an http request to the server for the first time, the server will create a session object, generate a sessionID to identify the session object, and then put the sessionID in the Cookie and send it to the client. The next time the http request is sent to the server , Http request will be sent to the server together with the sessionID obtained for the first time, and different users will be identified on the server side.

Insert picture description here

The above session tracking process is similar to the process of storing items in the lockers at the entrance of the supermarket when we go to the supermarket.
4.What is the difference between Session and Cookie?
Insert picture description here

5. Common methods
of HttpSession HttpSession interface in Servlet
1. Get the HttpSession interface object through the getSession() method of the HttpServletRequest
object 2. Common methods of HttpSession interface object
Insert picture description here

For example: the login operation uses the HttpSession object

package com.wangxing.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 创建登陆页面的Servet
 * @author Administrator
 *
 */
public class LoginServlet extends HttpServlet{

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置请求的字符编码
		req.setCharacterEncoding("utf-8");
		//设置响应的字符编码
		resp.setCharacterEncoding("utf-8");
		//得到输出流对象
		PrintWriter out=resp.getWriter();
		//输出一个登陆页面
		//out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset=\"utf-8\">");
		out.println("<title>登陆</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<center>");
		//得到session对象
		//1.通过HttpServletRequest对象的getSession()方法得到HttpSession接口对象
		HttpSession session=req.getSession();
		//输入session的基本信息
		showSessionInfo(out,session);
		//得到错误提示信息
		Object obj=session.getAttribute("errortip");
		if(obj!=null){
			String errortip=(String)obj;
			out.println("<font color=\"red\">"+errortip+"</font>");
		}
		out.println("<form action=\"cheack\" method=\"post\">");
		out.println("用户名:<input name=\"username\" type=\"text\"><br>");
		out.println("密码:<input name=\"password\" type=\"password\"><br>");
		out.println("<input type=\"submit\"  value=\"登陆\"/>");
		out.println("</form>");
		out.println("</center>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}
     /**
      * 输入session的基本信息
      * @param out
      * @param session
      */
	private void showSessionInfo(PrintWriter out, HttpSession session) {
		//得到session的基本信息
		//得到sessionID
		String sessionid=session.getId();
		//创建时间日期格式化对象
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
		//得到session对象的创建时间[毫秒]
		String createtime=sdf.format(new Date(session.getCreationTime()));
		//得到session的最后访问时间[毫秒]
		String lastAccesse=sdf.format(new Date(session.getLastAccessedTime()));
		//得到session的最大不活动时间[秒]
		int maxtime=session.getMaxInactiveInterval();
		//session对象是否是一个新的session对象
		boolean sessionnew=session.isNew();
		out.println("<table border=\"1px\">");
		out.println("<tr>");
		out.println("<td>sessionID</td>");
		out.println("<td>"+sessionid+"</td>");
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td>session对象的创建时间</td>");
		out.println("<td>"+createtime+"</td>");
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td>session的最后访问时间[毫秒]</td>");
		out.println("<td>"+lastAccesse+"</td>");
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td>session的最大不活动时间[秒]</td>");
		out.println("<td>"+maxtime+"</td>");
		out.println("</tr>");
		out.println("<tr>");
		out.println("<td>是否是一个新的session对象</td>");
		out.println("<td>"+sessionnew+"</td>");
		out.println("</tr>");
		out.println("</table>");
	}
}
package com.wangxing.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 创建验证用户名和密码的Servlet
 * @author Administrator
 *
 */
public class CheackServlet extends HttpServlet{

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置请求的字符编码
		req.setCharacterEncoding("utf-8");
		//设置响应的字符编码
		resp.setCharacterEncoding("utf-8");
		//得到用户名和密码
		String username=req.getParameter("username");
		String password=req.getParameter("password");
		//判断用户名和密码
		if(username.equals("zhangsan") && password.equals("123456")){
			//跳转到成功页面
			//封装用户名
			req.setAttribute("username", username);
			//请求转发
			req.getRequestDispatcher("/success").forward(req, resp);
		}else{
			//封装错误提示信息跳转到登陆页面
			//通过HttpSession对象封装数据
			//setAttribute用于向创建的session对象中保存数据
			req.getSession().setAttribute("errortip", "用户名密码不匹配");
			resp.sendRedirect("login");
		}
	}
}
package com.wangxing.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 创建登陆成功页面的Servet
 * @author Administrator
 *
 */
public class SuccessServlet extends HttpServlet{

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//从request中的得到username
		Object  obj=req.getAttribute("username");
		String username="";
		if(obj==null){
			resp.sendRedirect("login");
		}else{
			username=(String)obj;
		}
		//设置请求的字符编码
		req.setCharacterEncoding("utf-8");
		//设置响应的字符编码
		resp.setCharacterEncoding("utf-8");
		//得到输出流对象
		PrintWriter out=resp.getWriter();
		//输出一个登陆页面
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset=\"utf-8\">");
		out.println("<title>登陆</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<center>");
		out.println("<h1>"+username+",登陆成功!!!</h1>");
		out.println("<a href=\"logout\">安全退出</a>");
		out.println("</center>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}
}
package com.wangxing.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 退出的Servlet
 * @author Administrator
 *
 */
public class LogOutServlet extends HttpServlet{

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置请求的字符编码
		req.setCharacterEncoding("utf-8");
		//设置响应的字符编码
		resp.setCharacterEncoding("utf-8");
		//销毁session对象
		req.getSession().invalidate();
		resp.sendRedirect("login");
	}
}

4. What is the difference between Get and Post?
Insert picture description here

5. Chinese garbled processing
Web page----
Eclipse—window—>preferences—>General---->workspace---->Text file encoding
Tomcat—default character encoding "iso8859-1"
server/conf directory/ server.xml file

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  URIEncoding="UTF-8"/>

1. The Chinese page submitted to the Servlet handler is garbled.
Post submission method request.setCharacterEncoding("utf-8");
GET method String name = new String(name.getBytes("iso8859-1"),"utf-8 ");
2. The Chinese output from the Servlet handler to the page is garbled
response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type","text/html;charset=utf-8");

Guess you like

Origin blog.csdn.net/guoguo0717/article/details/109124528