Filter Filter, xml configuration and explanatory notes @WebFilter

<!-- Filter -->
 2     <filter>
 3         <!-- filter名可以随便起,但要与下面的mapping中的filter-name保持一致 -->
 4         <filter-name>SuiBian</filter-name>
 5         <!-- 实现类所在目录 -->
 6         <filter-class>com.filter.SuiBianFilter</filter-class>
 7     </filter>
 8 
 9     <!-- filter映射 -->
10     <filter-mapping>
11         <!-- 对应的filter名,和上边的filter名保持一致保持映射关系 -->
12         <filter-name>SuiBian</filter-name>
13         <!-- 要进行拦截过滤的目录 /*代表拦截全部。或者输入具体需要拦截的目录名-->
14         <url-pattern>/*</url-pattern>
15     <filter-mapping>
16

These are configured in the xml configuration file.



@WebFilter configuration
in a future version of the high web project, do not need to configure the xml, just need to write a plain java class that implements the Filter interface, the class can be explained @WebFilter. Said the following about how to configure @WebFilter.
@WebFilter common attributes of
Here Insert Picture Description
example:

package com.Filter;

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

@WebFilter(filterName = "MyFilter",urlPatterns = {"/FilterServlet"})
public class MyFilter implements javax.servlet.Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器的初始化init.....");
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("过滤器之前........");
        chain.doFilter(req, resp);
        System.out.println("过滤器之后........");
    }
    public void destroy() {
        System.out.println("过滤器的销毁destroy.....");
    }
}

Here Insert Picture Description
After urlPatterns, need to filter access to the code.
1, depending on the conditions to decide whether to call chain.doFilter (request, response) method, whether to make the target resource in the implementation of the filter
2, before letting the target resources to implement, can request \ response as pretreatment, let target resources to implement
3, after performing the target resource, the target resource execution result may be captured in order to achieve some special features
the doFilter () method is to intercept, chain.doFilter (req, resp); the code before the code is executed before the request, after the code when the code is executed in response; the init () method is executed when the server opens, and only once; the destroy () executed on the server is closed, and is performed only once.

Released six original articles · won praise 0 · Views 154

Guess you like

Origin blog.csdn.net/chen_wwww/article/details/104892864