Listener -, passivation, activation, using the listener to implement a simple version of the statistics website online user function

Listen to the status of an object bound to the HttpSession domain

1.HttpSessionBindingListener

Entity class

package com.etime.enetity;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

//Here you need to implement the HttpSessionBindingListener interface and re-invent the method
public class Student implements HttpSessionBindingListener{
    private String name;
    private int age;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("The" + event.getValue() + "The student is bound to the session");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("The" + event.getValue() + "The student was unbound from the session");
    }
}
<%@ page import="com.etime.enetity.Student" %><%--
  Created by IntelliJ IDEA.
  User:xx
  Date: 2023/9/2
  Time: 20:01
  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>
<%
    Student student1 = new Student("Zhang San", 23);
    Student student2 = new Student("李思", 21);
    Student student3 = new Student("zh", 21);
    session.setAttribute("stu1",student1);
    session.setAttribute("stu2",student2);
    session.setAttribute("stu1",student3);
    session.removeAttribute("stu1");
    session.removeAttribute("stu2");
%>
</body>
</html>

2..HttpSessionActivationListener

package com.etime.enetity;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import java.io.Serializable;

//Implement HttpSessionActivationListener and Serializable interfaces
public class Teacher implements HttpSessionActivationListener, Serializable {
    private String name;
    private int age;

    public Teacher() {
    }

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        System.out.println("passivated");
    }

    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println("activated");
    }
}
<%@ page import="com.etime.enetity.Teacher" %><%--
  Created by IntelliJ IDEA.
  User:xx
  Date: 2023/9/2
  Time: 20:20
  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>
<%--To test passivation, visit this page, then shut down the server and see if it is saved in the file--%>
<%
    Teacher teacher = new Teacher("张三", 23);
    session.setAttribute("teacher",teacher);
%>
</body>
</html>

<%--
  Created by IntelliJ IDEA.
  User:xx
  Date: 2023/9/2
  Time: 20:20
  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>
<%--Test activation, restart the service again and then directly access this page to see if the data still exists--%>
${teacher}
</body>
</html>

Statistical website online user function

Idea analysis: Listen through the ServletContextListener. When the Web application context is started, add a List collection in the ServletContext to prepare to store the online user name; then, you can use the HttpSessionAttributeListener listener to set the user name to the Session when the user logs in successfully. At the same time, the user name is stored in the List in the ServletContext; finally, through HttpSessionListener monitoring, when the user logs out of the session, the user name is deleted from the List in the application context scope.

Login interface

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="LoginServlet.ser" method="post">
    Username: <input type="text" name="username" ><br>
    Password: <input type="password" name="password" ><br>
    <input type="submit" value="Login">
</form>
</body>
</html>

home page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$<a href="OutLoginServlet.ser" >Exit login</a>
  Welcome, ${sessionScope.username}
  The users currently visiting this website are:
  <c:forEach var="str" items="${list}">
    ${str}
  </c:forEach>
  </body>
</html>

servlet

@WebServlet(name = "LoginServlet", value = "/LoginServlet.ser")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        boolean flag=true;
        if (flag){
            //Landed successfully
            HttpSession session = request.getSession();
            System.out.println(username);
            session.setAttribute("username",username);
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }else {
            //Login failed
        }
    }
}

sign out

@WebServlet(name = "OutLoginServlet", value = "/OutLoginServlet.ser")
public class OutLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();
        response.sendRedirect("login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

listener

@WebListener
public class UserLoginListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    ServletContext servletContext = null;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //Create a collection when the server starts to store users who visit this website
        List<String> list = new LinkedList<>();
        //Get the ServletContext object
        servletContext = sce.getServletContext();
        //Put the collection into the ServletContext object
        servletContext.setAttribute("list", list);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        //Put the username into the collection when the user logs in
        //Get session object
        HttpSession session = se.getSession();
        //Get KEY
        if ("username".equals(se.getName())) {
            //Put the username in the session into the collection.
            //Get username
            String username = (String) se.getValue();
            //String username = (String)session.getAttribute("username");
            //Get the collection
            List<String> list =(List<String>) servletContext.getAttribute("list");
            //Save data into collection
            list.add(username);
            //Finally put the collection back
            servletContext.setAttribute("list",list);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        //When the user exits, the session object is destroyed and the exiting user is removed from the collection.
        //Get session object
        HttpSession session = se.getSession();
        String username =(String) session.getAttribute("username");
        //Remove from the collection
        List<String> list =(List<String>) servletContext.getAttribute("list");
        list.remove(username);
        servletContext.setAttribute("list",list);
    }
}

Filter—Solving the problem of Chinese garbled characters–and unable to access the main page without logging in

@WebFilter("*.ser")
public class ChainFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Processing Chinese garbled characters
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        //release
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}
@WebFilter("/index.jsp")
public class indexFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        if (username==null){
            response.sendRedirect("login.jsp");
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}