Introduction and use of Filter

Filter

The syntax of MySql is enough to read this article. Delivery address: MySql must know
the use of JSP. It is enough to read this article. Delivery address: JSP must know and know

1. Introduction of Filter

  1. Filter is one of the three major components of JavaWeb, and the remaining components are: Servlet program, Listener listener
  2. Filter is a JavaEE specification, which is an interface
  3. The role of Filter is to intercept requests and filter responses

Second, the use of Filter

  1. Steps to use Filter:

(1) Write a class that implements the Filter interface (the imported package is: javax.servlet.Filter)

(2) Implement three methods: ①Implement the
filtering method doFilter(), in this method:
filterChain.doFilter(servletRequest, servletResponse);
Only by executing this method can you access the resources in the interception path, if this method is not executed, Representative interception
②implement init() method
③implement destroy() method

(3) Configure the interception path of Filter in web.xml

  1. Filter workflow:
    Insert picture description here

  2. Case: There is an Admin directory in the web directory. All resources in this directory can only be accessed after the user logs in.
    If there is no login, then jump to the login page

Analysis: After the user logs in, the login information will be saved in the Session field, so check whether the user is logged in, you can judge whether the session contains the user's login information.

Code demonstration (1): Create LoginServlet program

public class LoginServlet implements Filter {
    
    
    @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) {
    
       httpServletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
        } else {
    
    
            //登录成功,可以访问Admin目录下的目标资源
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
     }
    @Override
    public void destroy() {
    
     }
}

Code demonstration (2): write configuration in web.xml

<!--  Filter标签用于配置一个Filter过滤器,用法与Servlet标签一致  -->
<filter>
    <filter-name>LoginServlet</filter-name>
    <filter-class>com.qizegao.Filter.LoginServlet</filter-class>
</filter>
<filter-mapping>
    <filter-name>LoginServlet</filter-name>
    <!--  url标签用于配置拦截路径,也就是访问哪些资源需要被拦截  -->
    <!--  /表示工程路径,映射到web目录  -->
    <!--  /*代表指定目录下的所有文件  -->
    <url-pattern>/Admin/*</url-pattern>
</filter-mapping>

Running result:
directly input in the browser: http://localhost:8080/MyTest/Admin/a.jsp, jump to login.jsp, unable to access a.jsp

Note:
1. The Filter filter also supports annotations. Add @WebFilter("Intercepting Path") in the first line, and the web.xml file is not required
. 2. The browser cannot directly access the class that implements the Filter interface. Just access the interception path. Will automatically trigger the doFilter method

Third, the life cycle of Filter

1. Constructor method
2. init initialization method
3. doFilter method (including chain.doFilter method)
4. destroy method
Among them: ① 1 and 2 are executed when the web project starts (that is, when the filter is created)
② third Step: When a request that meets the interception path is sent to the server, it will be automatically executed. If the request does not belong to the interception
path, it will not be executed.
③ Step 4, executed when the web project is stopped (stopping the web project will also destroy the Filter filter) )

Fourth, the FilterConfig class

1. The FilterConfig class is the configuration file class of the Filter filter. Every time a Filter is created, a FilterConfig
class is also created , which contains the configuration information of the Filter configuration file

2. The role of the FilterConfig class is to obtain the configuration file content of the
Filter : (1) Get the name of the Filter, that is, the value of the tag in the web.xml file:
filterConfig.getFilterName();
(2) Get the tag in the web.xml file The value of (written in the filter tag, you can write multiple), such as:
Insert picture description here
(3) Get the ServletContext object: filterConfig.getServletContext()

Five, FilterChain filter chain

Role: to solve how multiple filters work together
Insert picture description here

note:

  1. The resource paths intercepted by the above two Filters are the same, which means that the doFilter method of the two Filters will be executed, but the chain.doFilter method may not be executed because of manual annotations.
  2. If the two Filter interception resources are different, and the interception resource meets Filter1 but not Filter2, the doFilter method of Filter1 will be executed, and when the chain.doFilter method is executed, the doFilter method of Filter2 will not be executed, and the resource will be directly accessed. Then execute the post code of Filter1 (all after chain.doFilter are post code)
  3. If the requested resource does not meet the interception path of filters 1 and 2, neither doFilter methods are executed
  4. The pre-code, chain.doFilter method, and post-code are all in the doFilter method

Six, Filter interception path

1. Exact match

<url-pattern>/target.jsp</url-pattern>

Indicates that the requested address must be http://ip:port/project path/target.jsp to trigger the doFilter method

2. Directory matching

<url-pattern>/admin/*</url-pattern>

Indicates that the requested address must be all the files in the http://ip:port/project path/admin/ directory to trigger the doFilter method

3. Suffix name matching

<url-pattern>*.html</url-pattern>

Indicates that the request address must end with .html to trigger the doFilter method

<url-pattern>*.jsp</url-pattern>

Indicates that the request address must end with .jsp to trigger the doFilter method

Note: Filter only cares about whether the requested address meets the interception path, not whether the requested resource exists

Code demonstration: the use of FilterChain filter chain
(1) Create a.jsp in the Admin directory
Insert picture description here

(2) Create two Filter filters

public class Filter1 implements Filter {
    
    
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
    
        System.out.println("Filter1的前置代码执行");
        chain.doFilter(req, resp);
        System.out.println("Filter1的后置代码执行");
    }
}

public class Filter2 implements Filter {
    
    
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
    
        System.out.println("Filter2的前置代码执行");
        chain.doFilter(req, resp);
        System.out.println("Filter2的后置代码执行");
    }
}

(3) Write configuration in web.xml
Insert picture description here

Running result:
input in the browser address bar: http://localhost:8080/MyTest/Admin/a.jsp
console output:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_49343190/article/details/108280836