13. Listner and Filter filters

Three components of Java Web. They are: Servlet program, Listener listener and Filter filter

1, Listener listener

  • Listener listener, which is one of the three major components of Java Web. The three major components of Java Web are Servlet program, Filter filter and listener listener.
  • Listener, which is the specification of Java EE, is the interface
  • The function of a listener is to monitor the change of something. Then through the callback function, feedback to the customer (program) to do some corresponding processing

ServletContextListener listener listener

ServletContextListener, which can listen to the creation and destruction of ServletContext objects.

The ServletContext object is created when the web project starts and destroyed when the web project stops. After listening to creation and destruction, the method feedback of ServletContextListener listener will be called respectively.

Use the ServletContextListener listener to listen for ServletContext objects. Steps:

1,Write a class to implement ServletContextListener
2,Implement its two callback methods
3,reach web.xml Configure listener in

Listener implementation class:

public class MyServletContextListenerImpl implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("ServletContext Object was created");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("ServletContext The object was destroyed");
    }
}

Configuration in web.xml:

<!--Configure listener-->
<listener>
    <listener-class>com.zb.listener.MyServletContextListenerImpl</listener-class>
</listener>

2, Filter 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 picture file or static html file, so as to realize some special functions. For example, it implements some advanced functions such as URL level permission access control, filtering sensitive words, compressing response information and so on.
  • The Servlet API provides a Filter interface. When developing web applications, if the Java class written implements this interface, this Java class is called Filter. Through Filter technology, developers can intercept requests and responses before accessing a target resource, as shown below:

Function summary: intercept requests and filter responses

2.2 use of filter

Use steps of Filter:

1,Write a class to implement Filter Interface
2,Implement filtering method doFilter()
3,reach web.xml De configuration in Filter Interception path

Code example:

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

Methods without filters:

We know that after a user logs in, the user login information will be saved to the Session domain. Therefore, to check whether the user logs in, you can judge whether the Session contains the user login information!!!

Methods of using filters: (key points)

Code of Filter:

public class AdminFilter implements Filter {
   /**
    * doFilter Method to intercept requests and filter responses
    * @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");
       //If it is equal to null, it indicates that you have not logged in
       if(user == null){
           >servletRequest.getRequestDispatcher("/index.jsp").forward(servletRequest,servletResponse);
           return ;
       }else{
           //Let the program continue to access the user's target resources
           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 Label is used to configure a Filter filter-->
   <filter>
       <!--to filter Create an alias-->
       <filter-name>AdminFilter</filter-name>
       <!--to configure filter Full class name of-->
       <filter-class>com.zb.filter.AdminFilter</filter-class>
   </filter>
   <!--filter-mapping to configure Filter Intercepting path of filter-->
   <filter-mapping>
       <!--filter-name Indicates to which of the current interception paths filter use-->
       <filter-name>AdminFilter</filter-name>
       <!--url-pattern Configure interception path
           / Indicates that the request address is: http://ip:port / Project path / web Directory mapped to IDEA
           /admin/* Indicates that the request address is: http://ip:port / Project path / admin/*
       -->
       <url-pattern>/admin/*</url-pattern>
   </filter-mapping>
</web-app>

2.3 Filter life cycle

The life cycle of Filter contains methods

1,Constructor method
2,init Initialization method
	Steps 1 and 2, in web Execute when the project starts( Filter (already created)
3,doFilter Filtering method
	Step 3: every time a request is intercepted, it will be executed
4,destroy Destroy
	Step 4, stop web When the project is completed, it will be executed (stopped) web The project will also be destroyed Filter Filter)

Creation of Filter
The web server is responsible for the creation and destruction of filters. When the web application starts, the web server will create an instance object of Filter and call its init method to complete the initialization function of the object, so as to prepare for interception of subsequent user requests. The Filter object will be created only once and the init method will be executed only once. The FilterConfig object representing the current Filter configuration information can be obtained through the parameters of the init method.

Destruction of Filter
The 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 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 that encapsulates the filter initialization parameters. Therefore, when writing filter, developers can obtain the following information through the method of filterConfig object:

  • 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, null is returned
  • 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. Get the name of Filter and the content of Filter name
        System.out.println("filter-name The values are:"+filterConfig.getFilterName());
        //2. Get the init param initialization parameters configured in web.xml
        System.out.println("Initialization parameters username The values are:"+filterConfig.getInitParameter("username"));
        System.out.println("Initialization parameters url The values are:"+filterConfig.getInitParameter("url"));
        //3. Get ServletContext object
        System.out.println(filterConfig.getServletContext());
    }

    /**
     * doFilter Method to intercept requests and filter responses
     * @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 of destroy method");
    }
}

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 Label is used to configure a Filter filter-->
    <filter>
        <!--to filter Create an alias-->
        <filter-name>AdminFilter</filter-name>
        <!--to configure filter Full class name of-->
        <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 to configure Filter Intercepting path of filter-->
    <filter-mapping>
        <!--filter-name Indicates to which of the current interception paths filter use-->
        <filter-name>AdminFilter</filter-name>
        <!--url-pattern Configure interception path
            / Indicates that the request address is: http://ip:port / Project path / web Directory mapped to IDEA
            /admin/* Indicates that the request address is: http://ip:port / Project path / admin/*
        -->
        <url-pattern>/admin/*</url-pattern>
    </filter-mapping>

</web-app>

2.5 FilterChain filter chain

The web server determines 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 will create a FilterChain object representing the filter chain and pass it to the 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 so, the second filter will be called. If not, the target resource will be called.

2.6 interception path of filter

  1. Exact match

     <url-pattern>/target.jsp</url-pattern>
     The path configured above indicates that the request address must be: http://ip:port / Project path / target.jsp
    
  2. Directory matching

     <url-pattern>/admin/*</url-pattern>
     The path configured above indicates that the request address must be: http://ip:port / Project path / admin/*
    
  3. Suffix matching

     <url-pattern>*.html</url-pattern>
     The path configured above indicates that the request address must be.html Will be intercepted at the end
     <url-pattern>*.do</url-pattern>
     The path configured above indicates that the request address must be.do Will be intercepted at the end
     <url-pattern>*.action</url-pattern>
     The path configured above indicates that the request address must be.action Will be intercepted at the end
     Filter The filter only cares about whether the requested address matches, not whether the requested resource exists!!!
    
  4. Wildcard matching

     <url-pattern>/*</url-pattern>
     Intercept all web resources.
    

Tags: Java mvc

Posted on Fri, 10 Sep 2021 15:51:11 -0400 by greg252