Simple application of Session and Cookie monitoring and filter interception, and small use of listener

What is session tracking technology

Session tracking is a common technology in Web programs, which is used to track the whole session of users. Maintain data management during user sessions. Common session tracking
Technology is Cookie and Session.
Cookie s determine the user's identity by recording information on the client
Session determines the user identity by recording information on the server.

1. What is a cookie

Cookie is an identification mark sent by the server to the client after the client (generally refers to the browser) requests the server, which is saved in the client. When the client again
When sending a request to the server, it will carry this identification, and the server can use this identification to identify the identity or status of the client.
Role of cookies: track sessions and record sessions in a Session. There may be multiple requests in a Session. Of course, there can also be multiple cookies
Track different information, so that the server will know the user's status, such as whether the login is successful, the things in the shopping cart during payment, etc
The note pasted on the forehead of the client can't be seen by the browser, but can be seen by the server

2. Application of cookies

2.1 maintain user login status
Save 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 can access it later
When the website, it will take the Cookie with it. The server will use it to identify the user, and the user will no longer need to enter user name, password and other information.
2.2 record user name
Once the user logs in successfully, the user name in the Cookie will be directly read and displayed when logging in again next time, so that the user does not need to enter again
User name, just enter the password.

3. Setting and obtaining cookies

3.1. Through httpservletresponse Set cookies by addcookie

Note: both parameters are strings when new Cookie()

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

3.2. View the contents of cookie s in the browser

Let's take a look at a simple application of cookie s:
The name of the account we entered on the client through the form: but when the input is wrong, we will return to this page, but in the column filled in this form, it is empty, so we hope it is not empty when we jump back. We need a cookie to operate and save this value through a cookie
Next, let's look at an example:

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 15:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>index.jsp</h1>
<a href="/testcookies">testcookies</a>
<p>


<%
        String val="";
        Cookie[] cookies = request.getCookies();//A cookie object is obtained through the request object and coexisted in the cookie array
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")){
                     val = cookie.getValue();
                     break;
                }
            }
        }
        request.setAttribute("val",val);//Note that we use the el expression to get the value later, so we must use setAttribute to save the value into the scope here

        %>
<form method="post" action="/login">
   user name:<input type="text" name="uname" value="${val}">
    <input type="submit" value="Sign in">
</form>
</p>
</body>
</html>

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 java.io.IOException;
@WebServlet(value = "/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);//Create a cookie object
            resp.addCookie(cookie);//Add a cookie through the response object
            resp.sendRedirect("/index.jsp");//Jump page
        }
    }
}

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 18:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Login successful</h1>
</body>
</html>

Let's take a look at the effect of operation:



After we failed to log in, the account number filled in by the user is still in our input box

4. Delete cookies

By setting the maximum lifetime of a Cookie with the same name to 0, deleting a Cookie means that the browser will no longer save the Cookie and invalidate the Cookie immediately
Example: invalidate the Cookie whose name is username immediately

//1. Create a cookie whose name is username. Cookie = new cookie ("username",
“aaa”); // 2. Set the effective time of the cookie to 0 setMaxAge(0);// Key to deleting cookies
//3. Send the cookie to the browser to replace the cookie response with the same name addCookie(cookie);

Effective time of Cookie
After the Cookie is sent to the browser, the browser will not save it permanently, that is, after a certain time, the browser will automatically destroy the Cookie.
The default effective time of cookies is one session (a process of opening and closing the browser). We can also manually specify the effective time of cookies

//setMaxAge is used to set the maximum effective time of a Cookie. An int type parameter is required to represent the valid seconds setMaxAge (seconds);
//When the parameter is greater than 0, it will be set to the specified number of seconds cookie setMaxAge(30);
//When the parameter is equal to 0, the browser will not save the cookie, and the cookie will expire immediately setMaxAge(0);
//When the parameter is less than 0, the current session has a valid cookie as if it were not set setMaxAge(-100);
//Setting a permanently valid Cookie is not permanent, it just makes the Cookie live for a long time
cookie.setMaxAge(60602436510);

Session

What is a Session
Session is another mechanism to record the status of customers. The difference is that cookies are saved in the client browser, while session is saved on the server. customer
When the client browser accesses the server, the server records the client information on the server in some form. This is Session. Client browser re
During this visit, you only need to find the status of the customer from the Session.
If the Cookie mechanism determines the identity of the client by checking the "pass" on the client, the Session mechanism determines the identity of the client by checking the "pass" on the server
To confirm the customer's identity. Session is equivalent to a customer file established by the program on the server. When the customer visits, he only needs to query
Just the customer file form.
2. Create Session format
The class corresponding to Session is javax servlet. http. Httpsession class. Each visitor corresponds to a Session object and all the status information of the customer
Are saved in this Session object. The Session object is created when the client first requests the server.
Session is also a key value attribute pair through getattribute (string key) and setAttribute(String key, Objectvalue) methods
Read and write customer status information. Request. In Servlet The getsession () method obtains the Session of the customer
For example:

HttpSession session = request.getSession(); // Get Session object
session.setAttribute(“loginTime”, new Date()); // Set properties in Session
out.println("login time:" + (date) session getAttribute(“loginTime”)); //
Get Session property

3. Life cycle of session
The Session is saved on the server side. In order to obtain higher access speed, the server usually puts the Session in memory. Each user will have an independent
Session. If the session content is too complex, memory overflow may occur when a large number of clients access the server. Therefore, the information in the session
It 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 a session is created only when accessing JSP, Servlet and other programs
Accessing static resources such as HTML and IMAGE does not create a Session. If the Session has not been generated, you can also make request Getsession (true) strong
Create a Session.
After a 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. User per access service
Server once. The server thinks that the user's Session is "active" once regardless of whether the Session is read or written. Since more and more users will access the server, there will be more and more sessions. In order to prevent memory overflow, the server will not live for a long time
The Session of the jump is deleted from memory. This time is the timeout of the Session. If the timeout period is exceeded and the server is not accessed, the Session starts automatically
The actuator failed.
The timeout time of the Session is the maxinactivitinterval attribute, which can be obtained through the corresponding getmaxinactivitinterval()
Setmaxinactivitinterval (longinterval) modification.
The Session timeout can also be displayed on the web Modify in 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. Common methods of session


5. Application scenario of session
Let's take an example: after we log in successfully, we use session to store the user's name in the page
Then it will be displayed

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 15:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>index.jsp</h1>
<a href="/testcookies">testcookies</a>
<p>


<%
        String val="";
        Cookie[] cookies = request.getCookies();//A cookie object is obtained through the request object and coexisted in the cookie array
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")){
                     val = cookie.getValue();
                     break;
                }
            }
        }
        request.setAttribute("val",val);//Note that we use the el expression to get the value later, so we must use setAttribute to save the value into the scope here

        %>
<form method="post" action="/login">
   user name:<input type="text" name="uname" value="${val}">
    <input type="submit" value="Sign in">
</form>
</p>
</body>
</html>

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 java.io.IOException;
@WebServlet(value = "/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);//Return a session object through the getSession() method, and then call the setAttribute method to store the value in the session
            resp.sendRedirect("/success.jsp");//Redirection will lose the data in the request, so we use a larger scope
        }else {
            Cookie cookie = new Cookie("username", uname);//Create a cookie object
            resp.addCookie(cookie);//Add a cookie through the response object
            resp.sendRedirect("/index.jsp");//Jump page
        }
    }
}

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 18:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Welcome:${loginuname}come back</h1>
</body>
</html>


Next, let's look at an example of listening to a session with session

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 15:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>index.jsp</h1>
<a href="/testcookies">testcookies</a>
<p>


<%
        String val="";
        Cookie[] cookies = request.getCookies();//A cookie object is obtained through the request object and coexisted in the cookie array
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")){
                     val = cookie.getValue();
                     break;
                }
            }
        }
        request.setAttribute("val",val);//Note that we use the el expression to get the value later, so we must use setAttribute to save the value into the scope here

        %>
<form method="post" action="/login">
   user name:<input type="text" name="uname" value="${val}">
    <input type="submit" value="Sign in">
</form>
</p>
</body>
</html>

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 java.io.IOException;
@WebServlet(value = "/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);//Return a session object through the getSession() method, and then call the setAttribute method to store the value in the session
            resp.sendRedirect("/success.jsp");//Redirection will lose the data in the request, so we use a larger scope
        }else {
            Cookie cookie = new Cookie("username", uname);//Create a cookie object
            resp.addCookie(cookie);//Add a cookie through the response object
            resp.sendRedirect("/index.jsp");//Jump page
        }
    }
}

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 18:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Welcome:${loginuname}come back<a href="/loginout">sign out</h1>
</body>
</html>

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

@WebServlet(value = "/loginout")
public class loginoutServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Disable session
        HttpSession session = req.getSession();//First get the session object
        session.removeAttribute("loginuname");//The first scheme is to delete only one value
        session.invalidate();//Make all session related values disappear
        resp.sendRedirect("index.jsp");
    }
}

Let's look at the effect:

After clicking exit, the value in the session will disappear

The difference between session and cookie:

(1) The cookie data is saved on the client side and the Session data is saved on the server side.
(2) Session is a server-side storage space maintained by the application server. When users connect to the server, the server will generate a unique session
SessionID, which is used as the identifier to access the Session storage space on the server side. The SessionID data is saved to the customer
The Session ID will be submitted to the server to access the Session data when the user submits the page. This process is
Without developer intervention. Therefore, 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. They exist in the customer service side memory or one
In the text file of the Cookie; Session will occupy server resources. Therefore, try not to use session but Cookies. But we
It is generally believed that Cookies are unreliable. Cookie s are saved on the machine, but their information is fully visible and easy to edit locally, so they can often be used
Causing a lot of security problems, Session is reliable. But at present, many famous sites also use cookies.

Filter

1. What is a filter
The filter is actually to intercept the web resources, do some processing, and then hand it over to the next filter or servlet for processing. It is usually used to intercept
If the request is processed, the returned response can also be intercepted
(take chestnuts for example: when people comment, it is equivalent to a request. In this request, we can create a filter to filter the comments)

2. Syntax format of filter
2.1. Create a class to implement the Filter interface

public class CharSetFilter implements Filter{}

2.2. Override methods in interfaces

public void destroy() { //Method of destruction}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws
ServletException, IOException {
//The filtering method is mainly to process the request and response, and then hand them over to the next filter or Servlet
 reason
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
/*The initialization method receives a parameter of FilterConfig type, which is some configuration of Filter*/
}

2.3. On the web Configuration in XML file

<filter>
<filter-name>Filter name</filter-name>
<filter-class>Path where the filter is located</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter name</filter-name>
<url-pattern>Resources to be filtered</url-pattern>
</filter-mapping>

Note: when there are multiple filters between the client and the server, the filter executed first ends at last. This can be understood by looking at the execution diagram above, that is, it goes through first and comes back at last

3. Usage scenario

3.1. How to prevent users from performing subsequent operations without logging in
String name=(String)session.getAttribute("key");
if(name==null){
//Jump to login page
}
3.2. Set encoding method – set encoding uniformly
3.3. Encryption and decryption (encryption and decryption of password)
3.4. Illegal text filtering
3.5. Restrictions on download resources
Filter features: it will be executed before and after the servlet

Next, let's take a look at the little chestnut to prevent users from performing subsequent operations without logging in:

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 15:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>index.jsp</h1>
<a href="/testcookies">testcookies</a>
<p>


<%
        String val="";
        Cookie[] cookies = request.getCookies();//A cookie object is obtained through the request object and coexisted in the cookie array
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("username")){
                     val = cookie.getValue();
                     break;
                }
            }
        }
        request.setAttribute("val",val);//Note that we use the el expression to get the value later, so we must use setAttribute to save the value into the scope here

        %>
<form method="post" action="/login">
   user name:<input type="text" name="uname" value="${val}">
    <input type="submit" value="Sign in">
</form>
</p>
</body>
</html>

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 java.io.IOException;
@WebServlet(value = "/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);//Return a session object through the getSession() method, and then call the setAttribute method to store the value in the session
            resp.sendRedirect("/success.jsp");//Redirection will lose the data in the request, so we use a larger scope
        }else {
            Cookie cookie = new Cookie("username", uname);//Create a cookie object
            resp.addCookie(cookie);//Add a cookie through the response object
            resp.sendRedirect("/index.jsp");//Jump page
        }
    }
}

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/9
  Time: 18:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Welcome:${loginuname}come back<a href="/loginout">sign out</h1>
</body>
</html>

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

@WebServlet(value = "/loginout")
public class loginoutServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Disable session
        HttpSession session = req.getSession();//First get the session object
        session.removeAttribute("loginuname");//The first scheme is to delete only one value
        session.invalidate();//Make all session related values disappear
        resp.sendRedirect("index.jsp");
    }
}

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class filter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter initialization operation");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter start execution");
        HttpServletRequest request = (HttpServletRequest)servletRequest;//You need to force the object here
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");//Handle all servlet garbled problems
        //Deal with the problem of no login and no access
        String loginuname =(String) request.getSession().getAttribute("loginuname");
        String requestURL = request.getRequestURI();//Get the requested address
        System.out.println("requestURL="+requestURL);
        //Release some web pages (resources that users can access when logging in, or when the session has value)
        if (requestURL.endsWith("/")||requestURL.endsWith("message.jsp")||requestURL.endsWith("/index.jsp")||
        requestURL.endsWith("/login")||loginuname!=null){
            filterChain.doFilter(servletRequest,servletResponse);//Call the next servlet or filter
        }else {
            response.sendRedirect("/message.jsp");
        }
        System.out.println("End of filter execution");

    }

    @Override
    public void destroy() {

    }
}

<%--
  Created by IntelliJ IDEA.
  User: 15158
  Date: 2020/11/10
  Time: 8:53
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<h1>Please login first and then visit the login page<a href="index.jsp"></a></h1>
</body>
</html>

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>f1</filter-name>
        <filter-class>filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>f1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Next, let's look at the effect:


Listener

A listener is a component that listens to the state changes of a domain object. The related concepts of a listener are: event source: the monitored object (three domain objects)
request, session, servletContext) listener: listen to the event source object. Changes in the state of the event source object will trigger the listener to register for listening
Listener: bind the listener to the event source. Response behavior: the function code involved when the listener listens to the state change of the event source (written by the programmer)
Code)

2. Listener classification

The first dimension is divided according to the monitored objects: ServletRequest field, HttpSession field and ServletContext field. The second dimension is divided according to the monitored objects
Content: the creation and destruction of listening domain objects and the change of attributes of listening domain objects

3. Monitor the creation and destruction of three domain objects

Compilation steps of listener (key points):
Write a listener class to implement the listener interface. The method of covering the listener needs to be on the web Configure in XML - Register:

< listener > < listener class > the path where the listener is located < / listener class > < / listener >

ServletContextListener
Listener that listens to the creation and destruction of ServletContext domain
Lifecycle of Servlet domain
When to create: server starts creating when to destroy: server shuts down destroying
The main function of ServletContextListener listener
Initialization work: initialize objects, initialize data (load database driver and connection pool initialization) and load some initialized configuration files
(configuration file of spring) task scheduling (timer Timer/TimerTask)
HttpSessionListener
A listener that listens to the creation and destruction of the Httpsession domain
The lifecycle of the HttpSession object
When to create: first call request When to destroy when creating a getsession: the server is shut down and destroyed, and the session expires (30 minutes by default, which can be modified)
The default 30 minutes is on Tomcat's web XML, modify the expiration time of the current project is on the web of your own project XML), manual destruction
Main functions of HttpSessionListener listener:
Because the session object will be created by default every time you visit the website (the session attribute in the page instruction in the jsp page is true by default, that is, it will be created when being accessed
session), which can be used to count the people who have visited the website
ServletRequestListener
Listener that listens to the creation and destruction of ServletRequest domain
Lifecycle of ServletRequest
Create: a request is created for each request
Destroy: end of request
Same as above, omitting here is not very useful

Tags: Java Session servlet filter

Posted by asy1mpo on Sun, 08 May 2022 12:38:38 +0300