Study notes 8: Filter FIlter and Listener

FIlter

A filter is implemented by implementing a javax.servlet.Filter interface, in which there are three methods, init(), doFilter(), destroy()
are respectively executed in the corresponding actual

package com.hou.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/01")   //拦截路径  拦截所有的资源路径可以使用通配符 ("/*")
public class Filter01 implements Filter {
    
    
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        
    }

    /**
     * 过滤方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        
        //放行资源,一定别忘了,不放行程序就不会继续往下走了
        System.out.println("filter01资源过滤----");
        filterChain.doFilter(servletRequest, servletResponse);
        
    }

    public void destroy() {
    
    

    }
}

If there are multiple filters to form a filter chain, the one configured first will be executed first.

Access permission interception:

/**
 * 访问权限拦截
 */
@WebFilter("/*")
public class LoginAccessFilter implements Filter {
    
    
    public void init(FilterConfig filterConfig) throws ServletException {
    
    

    }

    /**
     * 功能:指定页面和请求放行,如果用户session不存在,拦截回login.jsp,如果存在,放行
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的路径
        String uri = request.getRequestURI();
        System.out.println(uri);

		//String类 的 contains 方法可以帮助查询有没有指定的字符序列
        //如果请求路径中包含/login.jsp 这一段字符就放行
        if (uri.contains("/login.jsp") || uri.contains("loginServlet")){
    
    
            filterChain.doFilter(request,response);
            System.out.println("放行-----");
            return;
        }
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user);

        if (user != null){
    
    
            filterChain.doFilter(request,response);
            return;
        }
        //如果不是指定路径的页面或查出用户session为空代表用户没登录,那么直接跳转回login.jsp
        response.sendRedirect("login.jsp");


    }

    public void destroy() {
    
    

    }
}

Listener

Introduction:

Web listener is a special class in Servlet, which is used to monitor specific events and actions in the web, such as the creation and destruction of ServletContext, HttpSession, and ServletRequest; or the creation, destruction, and modification of variables. You can add processing after the action to achieve monitoring.

Uses such as: counting the number of people online, etc...

Usage: implement corresponding monitoring interfaces such as HttpSessionListener, ServletRequestListener, etc...

Monitor the creation and destruction of Session: remember to add annotation @WebListener

package com.xxxx.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class Listener01 implements HttpSessionListener {
    
    
    /**
     * 在Session对象被创建时执行
     * @param httpSessionEvent
     */
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    
    
        System.out.println("监听:Session创建");
    }

    /**
     * Session对象被销毁时执行
     * @param httpSessionEvent
     */
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    
    

        System.out.println("监听:Session销毁");
    }
}

Small case: online statistics

Case highlights :

  1. When the listener monitors the session creation, it means that there is one more user, and the number of users should be +1. The opposite is true when the session is destroyed.
  2. Because the final data is to be returned to the Servlet control layer, we need to store the information of the number of people in the application domain, that is, in the ServletContext domain, so that the real-time number of people can be shared by all users. Otherwise, if it is stored in the session domain, the user can only See the number of people up to his session.

Listener class:

package com.xxxx.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 实现在线人数统计
 */
@WebListener
public class OnlineListener implements HttpSessionListener {
    
    
    private Integer onlineNumber = 0;

    /**
     * 当有新的session对象创建时,人数+1
     * @param httpSessionEvent
     */
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    
    
        onlineNumber++;
        //将更新的人数信息存如session
//        httpSessionEvent.getSession().setAttribute("onlineNumber",onlineNumber);
        httpSessionEvent.getSession().getServletContext().setAttribute("onlineNumber",onlineNumber);
    }

    /**
     * 当一个session对象销毁时,人数-1
     * @param httpSessionEvent
     */
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    
    
        onlineNumber--;
        //将更新的人数信息存如session
//        httpSessionEvent.getSession().setAttribute("onlineNumber",onlineNumber);
        httpSessionEvent.getSession().getServletContext().setAttribute("onlineNumber",onlineNumber);
    }
}

Servlet class:

package com.xxxx.servlet;

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("/onlineServlet")
public class OnlineServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        HttpSession session = request.getSession();

        String key = request.getParameter("key");
        //如果传如的参数为logout,则表示退出,销毁该用户的session
        if (key != null && "logout".equals(key)){
    
    
            session.invalidate();
            return;
        }
        Integer onlineNumber = (Integer) session.getServletContext().getAttribute("onlineNumber");
        response.getWriter().write("<h2>当前在线人数:"+onlineNumber+"</h2> <a href='onlineServlet?key=logout'>退出</a>");
    }
}

Guess you like

Origin blog.csdn.net/qq_40492885/article/details/115314670