Filter&Listener Filter&Listener

Table of contents

1. Filter

1.1 The concept of Filter

1.2 The role of Filter

1.3 Code Implementation of Filter

1.3.1 Achieving goals

1.4 Filter life cycle

1.4.1 Servlet life cycle

1.4.2 Filter life cycle and life cycle methods

1.5 Filter Matching Rules

1.5.1 Purpose of filter matching

1.5.2 Four matching rules

1.6 Filter chain

1.6.1 The concept of filter chain

1.6.2 Order of filter chains

1.6.3 Filter chain example

2. Listener

2.1 Introduction to Listener

2.1.1 The concept of listener

2.1.2 Classification of Servlet listeners

2.2 Use of ServletContextListener

2.2.1 Function

2.2.2 Usage Scenarios

2.2.3 Code implementation


1. Filter

1.1 The concept of Filter

        Filter : A Java class that implements a special interface (Filter). It implements the function of filtering request resources (jsp, servlet, html,). The filter is a program running on the server, which takes precedence over request resources (Servlet or jsp, html) before execution. Filter is one of the most practical technologies in javaweb technology

1.2 The role of Filter

        The role of Filter is to filter target resources (Servlet, jsp), and its application scenarios include: login permission check, solving website garbled characters, filtering sensitive characters, etc.

1.3 Code Implementation of Filter

1.3.1 Achieving goals

        Realize solving the Chinese garbled characters of the request parameters before the request reaches ServletDemo01

① Create ServletDemo01

web.xml code

<servlet>
    <servlet-name>servletDemo01</servlet-name>
    <servlet-class>com.atguigu.ServletDemo01</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servletDemo01</servlet-name>
    <url-pattern>/ServletDemo01</url-pattern>
</servlet-mapping>

ServletDemo01 code

public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("ServletDemo01接收到了一个请求..."+username);
    }
}

front page code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <form action="/webday12/demo01" method="post">
        用户名<input type="text" name="username"/><br/>
        <input type="submit"/>
    </form>
</body>
</html>

If there is no Filter at this time, the request sent by the client will directly reach ServletDemo01, and the Chinese request parameters will be garbled

② Create Encoding Filter

web.xml code

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>com.atguigu.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <!--url-pattern表示指定拦截哪些资源-->
    <url-pattern>/demo01</url-pattern>
</filter-mapping>

 EncodingFilter code

/**
 * 编写过滤器的步骤:
 * 1. 写一个类实现Filter接口,并且重写方法
 * 2. 在web.xml中配置该过滤器的拦截路径
 */
public class EncodingFilter implements Filter {
    @Override
    public void destroy() {
        
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //解决请求参数的乱码
        HttpServletRequest request = (HttpServletRequest) req;
        request.setCharacterEncoding("UTF-8");

        //每次有请求被当前filter接收到的时候,就会执行doFilter进行过滤处理
        System.out.println("EncodingFilter接收到了一个请求...");

        //这句代码表示放行
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        
    }

}

1.4 Filter life cycle

1.4.1 Servlet life cycle

① When to create a Servlet

The Servlet is created by default when the first request is received. We can <load-on-startup>configure the Servlet to be created when the server starts through the label.

② Servlet destruction timing

The servlet will be destroyed when the server is shut down or the project is removed from the server

1.4.2 Filter life cycle and life cycle methods

life cycle stage execution time life cycle method
create object When the web application starts init method, usually do initialization work in this method
Intercept request A matching request was received doFilter method, usually interception filtering is performed in this method
destroy Before the web application is uninstalled The destroy method, where resource release is usually performed

1.5 Filter Matching Rules

1.5.1 Purpose of filter matching

The purpose of filter matching is to specify which resources are to be intercepted by the current filter

1.5.2 Four matching rules

① Exact match

Specify the full path of the intercepted resource:

<!-- 配置Filter要拦截的目标资源 -->
<filter-mapping>
    <!-- 指定这个mapping对应的Filter名称 -->
    <filter-name>FilterDemo01</filter-name>

    <!-- 通过请求地址模式来设置要拦截的资源 -->
    <url-pattern>/demo01</url-pattern>
</filter-mapping>

/demo01The above example indicates that the resource whose  mapping path is to be intercepted

② Fuzzy matching

        Compared with exact matching, using fuzzy matching allows us to create a filter that can cover many target resources. It is not necessary to create a filter for each target resource, which improves development efficiency.

        After we configure the url-pattern to /user/*, as long as the request address starts with /user, it will be matched.

<filter-mapping>
    <filter-name>Target02Filter</filter-name>

    <!-- 模糊匹配:前杠后星 -->
    <!--
        /user/demo01
        /user/demo02
        /user/demo03
		/demo04
    -->
    <url-pattern>/user/*</url-pattern>
</filter-mapping>

Extreme case: /* matches all requests

③ Extension matching

<filter>
    <filter-name>Target04Filter</filter-name>
    <filter-class>com.atguigu.filter.filter.Target04Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Target04Filter</filter-name>
    <url-pattern>*.png</url-pattern>
</filter-mapping>

The above example means to intercept all .pngrequests ending with

1.6 Filter chain

1.6.1 The concept of filter chain

        A request may be filtered by multiple filters. Only when all filters are allowed can the request reach the target resource. If a certain filter is not allowed, the request cannot reach subsequent filters and target resources. Multiple filters The composed chain is the filter chain

1.6.2 Order of filter chains

        The execution order of each Filter in the filter chain is determined by the order of filter-mapping configuration in web.xml . If a Filter is configured using ServletName for matching rules, the execution priority of this Filter is lower

1.6.3 Filter chain example

① Create ServletDemo01

web.xml code

<servlet>
    <servlet-name>servletDemo01</servlet-name>
    <servlet-class>com.atguigu.ServletDemo01</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>servletDemo01</servlet-name>
    <url-pattern>/ServletDemo01</url-pattern>
</servlet-mapping>

ServletDemo01 code

public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ServletDemo01接收到了请求...");
    }
}

② Create multiple Filters to intercept Servlets

<filter-mapping>
    <filter-name>TargetChain03Filter</filter-name>
    <url-pattern>/Target05Servlet</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>TargetChain02Filter</filter-name>
    <url-pattern>/Target05Servlet</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>TargetChain01Filter</filter-name>
    <url-pattern>/Target05Servlet</url-pattern>
</filter-mapping>

2. Listener

2.1 Introduction to Listener

2.1.1 The concept of listener

        Listener : An object that is specially used to monitor and process events or state changes that occur on other objects, and take corresponding actions immediately when something happens to the monitored object.

        Servlet listener : A special class defined in the Servlet specification, which is used to monitor the creation and destruction events of domain objects such as ServletContext, HttpSession, and HttpServletRequest in web applications, as well as the events of modifying properties in these domain objects.

2.1.2 Classification of Servlet listeners

① ServletContextListener

Role: monitor the creation and destruction of ServletContext objects

method name effect
contextInitialized(ServletContextEvent sce) Called when ServletContext is created
contextDestroyed(ServletContextEvent sce) Called when the ServletContext is destroyed

The ServletContextEvent object represents the event captured from the ServletContext object, through which we can get the ServletContext object.  

② HttpSessionListener

Role: monitor the creation and destruction of HttpSession objects

method name effect
sessionCreated(HttpSessionEvent hse) Called when the HttpSession object is created
sessionDestroyed(HttpSessionEvent hse) Called when the HttpSession object is destroyed

The HttpSessionEvent object represents the event captured from the HttpSession object, through which we can get the HttpSession object that triggered the event.

③ ServletRequestListener

Role: monitor the creation and destruction of ServletRequest objects

method name effect
requestInitialized(ServletRequestEvent sre) Called when the ServletRequest object is created
requestDestroyed(ServletRequestEvent sre) Called when the ServletRequest object is destroyed

The ServletRequestEvent object represents the event captured from the HttpServletRequest object. Through this event object, we can get the HttpServletRequest object that triggered the event. In addition, there is another method to get the ServletContext object of the current web application.

④ ServletContextAttributeListener  

Role: monitor the addition, removal and modification of attributes in the ServletContext

method name effect
attributeAdded(ServletContextAttributeEvent scab) Called when an attribute is added to the ServletContext
attributeRemoved(ServletContextAttributeEvent scab) Called when an attribute is removed from the ServletContext
attributeReplaced(ServletContextAttributeEvent scab) Called when an attribute in the ServletContext is modified

The ServletContextAttributeEvent object represents an attribute change event, and it contains the following methods:

method name effect
getName() Get the modified or added attribute name
getValue() Get the attribute value that was modified or added
getServletContext() Get the ServletContext object

⑤ HttpSessionAttributeListener

Function: monitor the addition, removal and modification of attributes in HttpSession

method name effect
attributeAdded(HttpSessionBindingEvent se) Called when adding attributes to HttpSession
attributeRemoved(HttpSessionBindingEvent se) Called when an attribute is removed from the HttpSession
attributeReplaced(HttpSessionBindingEvent se) Called when an attribute in the HttpSession is modified

The HttpSessionBindingEvent object represents an attribute change event, and it contains the following methods:

method name effect
getName() Get the modified or added attribute name
getValue() Get the attribute value that was modified or added
getSession() Get the HttpSession object that triggered the event

⑥ ServletRequestAttributeListener

Function: monitor the addition, removal and modification of attributes in ServletRequest         

method name effect
attributeAdded(ServletRequestAttributeEvent srae) Called when an attribute is added to the ServletRequest
attributeRemoved(ServletRequestAttributeEvent srae) Called when an attribute is removed from a ServletRequest
attributeReplaced(ServletRequestAttributeEvent srae) Called when an attribute in the ServletRequest is modified

The ServletRequestAttributeEvent object represents an attribute change event, and it contains the following methods:

method name effect
getName() Get the modified or added attribute name
getValue() Get the attribute value that was modified or added
getServletRequest () Get the ServletRequest object that triggered the event

2.2 Use of ServletContextListener

2.2.1 Function

        ServletContextListener monitors the creation and destruction of the ServletContext object, because the ServletContext object is created when the server starts and destroyed when the server is shut down, so ServletContextListener can also monitor the startup and shutdown of the server

2.2.2 Usage Scenarios

        SpringMVC的时候,会用到一个ContextLoaderListener,这个监听器就实现了ServletContextListener接口,表示对ServletContext对象本身的生命周期进行监控。

2.2.3 代码实现

① 创建监听器类

/**
 * 编写监听器的步骤:
 * 1. 写一个类实现对应的:Listener的接口(我们这里使用的是ServletContextListener),并且实现它里面的方法
 *    1.1 contextInitialized()这个方法在ServletContext对象被创建出来的时候执行,也就是说在服务器启动的时候执行
 *    1.2 contextDestroyed()这个方法会在ServletContext对象被销毁的时候执行,也就是说在服务器关闭的时候执行
 *
 * 2. 在web.xml中注册(配置)监听器
 */

public class ContextLoaderListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("在服务器启动的时候,模拟创建SpringMVC的核心容器...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("在服务器启动的时候,模拟销毁SpringMVC的核心容器...");
    }
}

② 注册监听器

<listener>
    <listener-class>com.atguigu.listener.ContextLoaderListener</listener-class>
</listener>

Guess you like

Origin blog.csdn.net/rbx508780/article/details/127695777