Listener listener and Filter filter learning summary


The three major components of JavaWeb. They are: Servlet program, Listener, Filter

One, Listener

  • Listener is one of the three major components of JavaWeb. The three major components of JavaWeb are: Servlet program, Filter, Listener.
  • Listener is the specification of JavaEE, which is the interface
  • The role of the listener is to monitor changes in something. Then through the callback function, feedback to the customer (program) to do some corresponding processing

ServletContextListener listener

ServletContextListener It can monitor the creation and destruction of ServletContext objects.

The ServletContext object is created when the web project is started, and destroyed when the web project is stopped. After the creation and destruction are monitored, the method feedback of the ServletContextListener listener will be called respectively.

Use the ServletContextListener listener to monitor the use steps of the ServletContext object:

1、编写一个类去实现 ServletContextListener
2、实现其两个回调方法
3、到 web.xml 中去配置监听器

Listener implementation class:

public class MyServletContextListenerImpl implements ServletContextListener {
    
    
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
    
    
        System.out.println("ServletContext对象被创建了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
    
        System.out.println("ServletContext对象被销毁了");
    }
}

Configuration in web.xml:

<!--配置监听器-->
<listener>
    <listener-class>com.zb.listener.MyServletContextListenerImpl</listener-class>
</listener>

Two, Filter

2.1 Introduction to Filter

  • Filter is also called filter. WEB developers use Filter technology to intercept all web resources managed by the web server: such as Jsp, Servlet, static image files or static html files, etc., so as to achieve some special functions. For example, realize some advanced functions such as URL-level permission access control, filtering sensitive words, and compressing response information.
  • A Filter interface is provided in the Servlet API. When developing a web application, if the written Java class implements this interface, the Java class is called a filter. Through Filter technology, developers can realize that the user intercepts the access request and response before accessing a target resource, as shown below:
    Insert picture description here

Function summary: intercept request, filter response

2.2 Use of Filter

Filter use steps:

1、编写一个类去实现 Filter 接口
2、实现过滤方法 doFilter()
3、到 web.xml 中去配置 Filter 的拦截路径

Code example:

Requirements: There is an admin directory under your web project. All resources (html pages, jpg images, jsp files, etc.) in this admin directory must be accessed after the user logs in.

Ways not to use filters:

We know that after the user logs in, the user login information will be saved in the Session field. So to check whether the user is logged in, you can judge whether the user login information is included in the Session! ! !
Insert picture description here

How to use filters: (emphasis)

Filter code:

public class AdminFilter implements Filter {
     
     
   /**
    * doFilter方法,专门用户拦截请求,过滤响应
    * @param servletRequest
    * @param servletResponse
    * @param filterChain
    * @throws IOException
    * @throws ServletException
    */
   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     
     
       HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
       HttpSession session = httpServletRequest.getSession();
       Object user = session.getAttribute("user");
       //如果等于null,说明还没有登录
       if(user == null){
     
     
           >servletRequest.getRequestDispatcher("/index.jsp").forward(servletRequest,servletResponse);
           return ;
       }else{
     
     
           //让程序继续往下访问用户的目标资源
           filterChain.doFilter(servletRequest,servletResponse);
       }
   }
}

Configuration in web.xml:

<?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过滤器-->
   <filter>
       <!--给filter起一个别名-->
       <filter-name>AdminFilter</filter-name>
       <!--配置filter的全类名-->
       <filter-class>com.zb.filter.AdminFilter</filter-class>
   </filter>
   <!--filter-mapping配置Filter过滤器的拦截路径-->
   <filter-mapping>
       <!--filter-name表示当前的拦截路径给哪个filter使用-->
       <filter-name>AdminFilter</filter-name>
       <!--url-pattern 配置拦截路径
           / 表示请求地址为: http://ip:port/ 工程路径 / 映射到 IDEA 的 web 目录
           /admin/* 表示请求地址为: http://ip:port/ 工程路径 /admin/*
       -->
       <url-pattern>/admin/*</url-pattern>
   </filter-mapping>
</web-app>

2.3 Filter life cycle

Methods included in the life cycle of Filter

1、构造器方法
2、init 初始化方法
	第 1,2 步,在 web 工程启动的时候执行(Filter 已经创建)
3、doFilter 过滤方法
	第 3 步,每次拦截到请求,就会执行
4、destroy 销毁
	第 4 步,停止 web 工程的时候,就会执行(停止 web 工程,也会销毁 Filter 过滤器)

Create a Filter of
  creation and destruction Filter responsibility of the WEB server. When the web application is started, the web server will create an instance object of the Filter and call its init method to complete the initialization function of the object, so as to prepare for the interception of subsequent user requests. The filter object will only be created once, and the init method will also It will only be executed once. Through the parameters of the init method, a FilterConfig object representing the current filter configuration information can be obtained.

The destruction of the Filter
  Web container calls the destroy method to destroy the Filter. The destroy method is executed only once in the life cycle of the Filter. In the destroy method, you can release the resources used by the filter.

2.4 FilterConfig interface

When configuring the filter, users can use <init-param> to configure some initialization parameters for the filter. When the web container instantiates the Filter object and calls its init method, it will pass in the filterConfig object encapsulating the filter initialization parameters. Therefore, when a developer writes a filter, through the method of the filterConfig object, they can obtain:

  • String getFilterName(): Get the name of the filter.
  • String getInitParameter(String name): Returns the value of the initialization parameter with the name specified in the deployment description. If it does not exist, return null.
  • Enumeration getInitParameterNames(): Returns an enumeration collection of the names of all initialization parameters of the filter.
  • public ServletContext getServletContext(): Returns the reference of the Servlet context object.

Example: Use FilterConfig to get filter configuration information:

public class AdminFilter implements Filter {
    
    

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    

        // 1 、获取 Filter 的名称 filter-name 的内容
        System.out.println("filter-name的值是:"+filterConfig.getFilterName());
        //2 、获取在 web.xml 中配置的 init-param 初始化参数
        System.out.println("初始化参数username的值是:"+filterConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是:"+filterConfig.getInitParameter("url"));
        //3 、获取 ServletContext 对象
        System.out.println(filterConfig.getServletContext());
    }

    /**
     * doFilter方法,专门用户拦截请求,过滤响应
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
    
    
        System.out.println("Filter的destroy方法");
    }
}

web.xml configuration:

<?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过滤器-->
    <filter>
        <!--给filter起一个别名-->
        <filter-name>AdminFilter</filter-name>
        <!--配置filter的全类名-->
        <filter-class>com.zb.filter.AdminFilter</filter-class>

        <init-param>
            <param-name>username</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>url</param-name>
            <param-value>jdbc:mysql://localhost3306/test</param-value>
        </init-param>

    </filter>
    <!--filter-mapping配置Filter过滤器的拦截路径-->
    <filter-mapping>
        <!--filter-name表示当前的拦截路径给哪个filter使用-->
        <filter-name>AdminFilter</filter-name>
        <!--url-pattern 配置拦截路径
            / 表示请求地址为: http://ip:port/ 工程路径 / 映射到 IDEA 的 web 目录
            /admin/* 表示请求地址为: http://ip:port/ 工程路径 /admin/*
        -->
        <url-pattern>/admin/*</url-pattern>
    </filter-mapping>

</web-app>

2.5 FilterChain filter chain

The web server decides which Filter to call first according to the registration order of the Filter in the web.xml file. When the doFilter method of the first Filter is called, the web server creates a FilterChain object representing the Filter chain and passes it to this method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there is a filter in the FilterChain object. If there is, the second filter will be called. If not, the target resource will be called.
Insert picture description here

Code example:
Insert picture description here
execution result:
Insert picture description here

2.6 Filter interception path

  1. Exact match

     <url-pattern>/target.jsp</url-pattern>
     以上配置的路径,表示请求地址必须为:http://ip:port/工程路径/target.jsp
    
  2. Directory matching

     <url-pattern>/admin/*</url-pattern>
     以上配置的路径,表示请求地址必须为:http://ip:port/工程路径/admin/*
    
  3. Suffix name matching

     <url-pattern>*.html</url-pattern>
     以上配置的路径,表示请求地址必须以.html 结尾才会拦截到
     <url-pattern>*.do</url-pattern>
     以上配置的路径,表示请求地址必须以.do 结尾才会拦截到
     <url-pattern>*.action</url-pattern>
     以上配置的路径,表示请求地址必须以.action 结尾才会拦截到
     Filter 过滤器它只关心请求的地址是否匹配,不关心请求的资源是否存在!!!
    
  4. Wildcard matching

     <url-pattern>/*</url-pattern>
     拦截所有web资源。
    

Good blog:
Filter & Listener summarize
the difference between java filter, listener and interceptor

Guess you like

Origin blog.csdn.net/weixin_44630656/article/details/114296549