Session tracking and interceptor filters

Sesion和Cookie

What is session tracking technology

Session tracking is a commonly used technique in Web programs to track the user's entire session. Maintain data management during user sessions. The commonly used session tracking technologies are Cookie and Session.

Cookie determines user identity by recording information on the client

Session determines user identity by recording information on the server side

Cookie

1. What is a cookie

	Cookie是客户端(一般指浏览器)请求服务器后,服务器发给客户端的一个辨认标识,保存在客户端,当客户端再次向服务器发送请求时,会携带着这个辨认标识,服务器就可以通过这个标识来识别客户端的身份或状态等。
Cookie的作用:跟踪会话,记录一次会话中(即Session,一次会话可能会有多次请求,当然也可以有多个Cookie来跟踪不同的信息)的信息,这样服务器就会知道用户的状态,比如有没有登录成功,付款时购物车中的东西等,就相当于贴在客户端脑门上的纸条,浏览器看不到,但服务器看得到。

2. Cookie application

2.1 Keep the user logged in

Keep the user's information in the cookie and send it to the browser, and set the effective time to a longer time, so that the browser will carry the cookie when visiting the website in the future, and the server can use this to identify the user. No longer need to enter information such as user name and password.

2.2 Record user name

Once the user logs in successfully, the user name in the cookie is directly read and displayed when logging in next time, so that the user does not need to enter the user name again, just enter the password

Case: Verify the form, save cookies

LoginServlet.java

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        String uname = req.getParameter("uname");
        if("admin".equals(uname)){
    
    
            resp.sendRedirect("/success.jsp");
        }else {
    
    
            Cookie cookie = new Cookie("username", uname);
            resp.addCookie(cookie);
            resp.sendRedirect("/index.jsp");
        }
    }
}

index.jsp
    
    <%
  String val="";
      Cookie[] cookies = request.getCookies();
      if(cookies!=null){
    
    
        for (Cookie cookie : cookies) {
    
    
            if(cookie.getName().equals("username")) {
    
    
              val = cookie.getValue();
            }
        }
      }
      %>
    <form action="/login" method="post">
    用户名:<input type="text" name="uname" value="<%=val%>"><input type="submit" value="登录">
    </form>

3. Cookie setting and acquisition

3.1 Set Cookie by HTTP Servlet Response.addCookie

Note: Both parameters in new Cookie() are strings

Cookie cookie = new Cookie("jieguo","true");
response.addCookie(cookie);

<%
    Cookie[] cookies = request.getCookies();
    if(cookies!=null){
    
    
        for(int i=0; i<cookies.length;i++){
    
    
            out.print("cookieName="+cookies[i].getName()+"cookieValue="+cookies[i].getValue());
        }
    }
%>

3.2. View the content of cookies in the browser

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-S4TWqHD0-1610805422037) (D:\Study\JavaEE New Class————Development\Chapter 7- Java web\Section 5-Filter and Listener\courseware and notes\document\effect.png)]

3.3. The server obtains the cookie carried by the client: obtained through HttpServletRequest

<%
Cookie[] cookies = request.getCookies();
    if(cookies != null)
        for(Cookie c : cookies){
    
    
            String name = c.getName();//获取Cookie名称
            if("jieguo".equals(name)){
    
    
            	String value = c.getValue();//获取Cookie的值
            	bool = Boolean.valueOf(value);//将值转为Boolean类型
    }
}
%>

4. Delete Cookies

By setting the maximum survival time of the cookie with the same name to 0, deleting the cookie means that the browser no longer saves the cookie, making the cookie invalid immediately

Example: to invalidate the cookie whose name is username immediately

//1.创建一个name为username的Cookie
Cookie cookie = new Cookie("username", "aaa");
//2.设置Cookie的有效时间为0
cookie.setMaxAge(0);//删除cookie的关键
//3.将cookie发送给浏览器,来替换同名Cookie
response.addCookie(cookie);

Cookie validity time

After the cookie is sent to the browser, the browser will not save it permanently, that is, the browser will automatically destroy the cookie after a certain period of time.

The default validity time of a cookie is one session (a process of opening and closing the browser once), we can also manually specify the validity time of the cookie

//setMaxAge用来设置Cookie的最大有效时间,需要int型的参数,代表有效的秒数
cookie.setMaxAge(秒数);
//当参数大于0时,会设置为指定的秒数
cookie.setMaxAge(30);
//当参数等于0时,浏览器不会保存Cookie,Cookie立即失效
cookie.setMaxAge(0);
//当参数小于0时,和不设置是一样,当前会话有效
cookie.setMaxAge(-100);
//设置一个永久有效的Cookie,并非永久,只是使Cookie的生命很长而已
cookie.setMaxAge(60*60*24*365*10);

Session

1. What is Session

Session is another mechanism for recording client status. The difference is that the Cookie is stored in the client browser, while the Session is stored on the server. When the client browser accesses the server, the server records the client information on the server in some form. This is Session. When the client browser visits again, it only needs to find the state of the client from the Session.

If the Cookie mechanism is to determine the identity of the customer by checking the "passport" on the customer, then the Session mechanism is to confirm the identity of the customer by checking the "customer list" on the server. Session is equivalent to a client file created by the program on the server. When a client visits, it only needs to query the client file table.

2. Create Session format

The class corresponding to Session is javax.servlet.http.HttpSession. Each visitor corresponds to a Session object, and all the state information of the client is stored in this Session object. The Session object is created when the client requests the server for the first time.

Session is also a key-value attribute pair, which reads and writes customer status information through the getAttribute (Stringkey) and setAttribute (String key, Objectvalue) methods. Get the client's Session in the Servlet through the request.getSession() method

E.g:

HttpSession session = request.getSession(); // 获取Session对象
session.setAttribute("loginTime", new Date()); // 设置Session中的属性
out.println("登录时间为:" +(Date)session.getAttribute("loginTime")); // 获取Session属性

3. Session life cycle

Session is stored on the server side. In order to obtain higher access speed, the server generally puts the Session in the memory. Each user will have an independent Session. 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 is automatically created when the user accesses the server for the first time. It should be noted that the Session will only be created when accessing programs such as JSP and Servlet. Only accessing static resources such as HTML and IMAGE will not create a Session. If the Session has not been generated yet, you can also make request.getSession(true) force a Session to be generated

After the session is generated, as long as the user continues to access, the server will update the last access time of the session and maintain the session. Every time a user visits the server, the server considers the user's session to be "active" once regardless of whether the session is read or written.

As more and more users will access the server, there will be more and more sessions. To prevent memory overflow, the server will delete sessions that have not been active for a long time from memory. This time is the timeout period of the Session. If the server is not accessed after the timeout period, the session will automatically become invalid.

The timeout period of the Session is the maxInactiveInterval attribute, which can be obtained through the corresponding getMaxInactiveInterval() and modified through setMaxInactiveInterval(longinterval).

Session timeout time can also be modified in web.xml. In addition, the Session can be invalidated by calling the invalidate() method of the Session.

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

4. Session common methods

5. Application scenarios of Sesssion

Code demonstration: 1. Login 2. Exit (Create Session and Eliminate Session)

Case

LoginServlet.java

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        String uname = req.getParameter("uname");
        if("admin".equals(uname)){
    
    
            req.getSession().setAttribute("loginuname",uname);
            resp.sendRedirect("/success.jsp");

        }else {
    
    
            Cookie cookie = new Cookie("username", uname);
            resp.addCookie(cookie);
            resp.sendRedirect("/index.jsp");
        }
    }
}

LoginOutServlet.java
    @WebServlet(value="/loginOut")
public class LoginOutServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //让session失效
        HttpSession session = req.getSession();
        //  session.removeAttribute("loginuname");
        session.invalidate();//让所有的session相关值都清除
        resp.sendRedirect("index.jsp");
    }
}

index.jsp
    
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1>index.jsp</h1>
  <a href="/testCookie">testCookie</a>
  <p>
  <%
  String val="";
      Cookie[] cookies = request.getCookies();
      if(cookies!=null){
    
    
        for (Cookie cookie : cookies) {
    
    
            if(cookie.getName().equals("username")) {
    
    
              val = cookie.getValue();
            }
        }
      }
      %>
    <form action="/login" method="post">
    用户名:<input type="text" name="uname" value="<%=val%>"><input type="submit" value="登录">
    </form>
  </p>
  </body>
</html>
        
success.jsp
        
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>登录成功</h1>
<h1>欢迎您:${
    
    loginuname}  <a href="/loginOut">退出</a></h1>
</body>
</html>

6. The difference between Session and Cookie

(1) Cookie data is stored on the client side, and Session data is stored on the server side.

(2) Session is a server-side storage space maintained by the application server. When a user connects to the server, the server will generate a unique SessionID, and use the SessionID as an identifier to access the server-side Session storage space. The SessionID data is saved to the client and saved with cookies. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process does not require developer intervention. So once the client disables cookies, the session will also become invalid.

(3) Cookies are a kind of Session object. But there is a difference. Cookies do not occupy server resources, but are stored in the client memory or a text file of Cookie; while Session will occupy server resources. Therefore, try not to use Session and use Cookies. However, we generally think that Cookies are unreliable. Cookies are stored on this machine, but the complete visibility of their information and easy local editability can often cause many security problems. Session is reliable. But now many well-known sites also use cookies.

Filter

1. What is a filter

Filters actually intercept web resources, do some processing, and then pass them to the next filter or servlet for processing. They are usually used to intercept the request for processing, and the returned response can also be intercepted.
Insert picture description here

import javax.servlet.*;

2. The syntax format of the filter

2.1. Create a class to implement the Filter interface

public class CharSetFilter implements Filter{
    
    }

2.2. Rewrite methods in the interface

public void destroy() {
    
     //销毁的方法}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws
ServletException, IOException {
    
    
        //过滤方法 主要是对request和response进行一些处理,然后交给下一个过滤器或Servlet处理
        chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
    
    
/*初始化方法 接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
}

2.3. Configure in the web.xml file

<filter>
    <filter-name>过滤器名称</filter-name>
    <filter-class>过滤器所在的路径</filter-class>
</filter>
<filter-mapping>
    <filter-name>过滤器名称</filter-name>
    <url-pattern>需要过滤的资源</url-pattern>
</filter-mapping>

3. Usage scenarios

3.1. How to prevent users from performing subsequent operations without logging in

String name=(String)session.getAttribute(“key”);

if(name==null){

//Jump to the login page

}

3.2. Set the encoding method-set the encoding uniformly

3.3. Encryption and decryption (encryption and decryption of passwords)

3.4. Illegal text screening

3.5. The characteristics of the restriction filter of downloaded resources: it will be executed before and after the servlet

Listener

1. What is a listener

A listener is the related concept of a component listener that monitors the state changes of a domain object: Event source: the object being monitored (three domain objects request, session, and servletContext) Listener: monitors the state of the event source object, event source object The change will trigger the listener to register the listener: bind the listener to the event source. Response behavior: the functional code involved when the listener monitors the state change of the event source (code written by the programmer)

2. Listener classification

The first dimension is divided according to the object being monitored: ServletRequest domain, HttpSession domain, and ServletContext domain. The second dimension is divided according to the content of monitoring: the creation and destruction of the monitoring domain object, and the attribute change of the monitoring domain object

Insert picture description here

3. Listeners that monitor the creation and destruction of three major domain objects

The preparation steps of the listener (emphasis):

Write a listener class to implement the listener interface to cover the listener method needs to be configured in web.xml-registration

<listener>
	<listener-class>监听器所在的路径</listener-class>
</listener>
ServletContextListener
监听ServletContext域的创建与销毁的监听器

Servlet域的生命周期
何时创建:服务器启动创建 何时销毁:服务器关闭销毁

ServletContextListener监听器的主要作用
初始化的工作:初始化对象、初始化数据(加载数据库驱动、连接池的初始化) 加载一些初始化的配置文件
(spring的配置文件) 任务调度(定时器—Timer/TimerTask)

HttpSessionListener
监听Httpsession域的创建和销毁的监听器

HttpSession对象的生命周期
何时创建:第一次调用request.getSession时创建 何时销毁:服务器关闭销毁、session过期(默认30分钟,修改
默认的30分钟是在Tomcat的web.xml,修改当前项目的过期时间是在自己项目的web.xml中)、手动销毁

HttpSessionListener监听器的主要作用:
由于每次访问网站都会默认创建session对象(jsp页面中page指令中的session属性默认为true,即被访问时创建
session),可以用于计数网站访问过的人

ServletRequestListener
监听ServletRequest域创建与销毁的监听器

ServletRequest的生命周期
创建:每一次请求都会创建request
销毁:请求结束
用法同上,用处不是很大,此处省略。
HttpSession对象的生命周期
何时创建:第一次调用request.getSession时创建 何时销毁:服务器关闭销毁、session过期(默认30分钟,修改
默认的30分钟是在Tomcat的web.xml,修改当前项目的过期时间是在自己项目的web.xml中)、手动销毁

HttpSessionListener监听器的主要作用:
由于每次访问网站都会默认创建session对象(jsp页面中page指令中的session属性默认为true,即被访问时创建
session),可以用于计数网站访问过的人

ServletRequestListener
监听ServletRequest域创建与销毁的监听器

ServletRequest的生命周期
创建:每一次请求都会创建request
销毁:请求结束
用法同上,用处不是很大,此处省略。

Guess you like

Origin blog.csdn.net/weixin_43515837/article/details/112725708