Simple introduction to filter

The article was first published in: https://blog.csdn.net/Sky_QiaoBa_Sum/article/details/105042151

Filter filter

The function of the filter is actually well understood: if I allow you to pass, you can pass. If I don't allow you to pass, there is no way to pass. Of course, there are still ways to pass, but the decision is up to the filter. Maybe if the filter processes you, you can reach the standard of passing.

Hey, that's almost what I mean. When we were writing servlets, we could not forget to add the following two sentences at the beginning when we encountered a request or response with Chinese characters to ensure uniform encoding and decoding in the process of processing requests and sending responses, right

//请求乱码处理
request.setCharacterEncoding("utf-8");
//响应乱码处理
response.setContentType("text/html;charset=utf-8");

Just think, if there are many servlets that need to be processed in this way, will it be more troublesome? Since they all need it, I can process the request before they enter the servlet and the response after they come out, which will be much more convenient.

    //可提取为初始化参数,这里默认utf-8了
	private String encode = "utf-8";
    public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain) throws ServletException,IOException {
        //全局响应乱码解决
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding(encode);
        response.setContentType("text/html;charset="+encode);
        chain.doFilter(request,response);
    }

At this time, the filter in the web can be introduced: once the resource path accessed by the other party matches the interception path configured by URL pattern, its request object can be intercepted. After interception, you can choose to release or add some small operations. Through the filter, we can complete many general operations, such as login verification, unified coding, etc.

Filter interface

All customizations must implement javax servlet. Filter interface. The following are the three methods defined in the interface.

public interface Filter {
	//web应用加载进容器,Filter对象创建之后,执行init方法初始化,用于加载资源,只执行一次。
    void init(FilterConfig var1) throws ServletException;
    //每次请求或响应被拦截时执行,可执行多次。
    void doFilter(ServletRequest var1,ServletResponse var2,FilterChain var3) throws IOException,ServletException;
    //web应用移除容器,服务器被正常关闭,则执行destroy方法,用于释放资源,只执行一次。
    void destroy();
}

Detailed explanation of parameters

Filterconfig VAR1: represents that the current filter is on the web Configuration information object in XML.

ServletRequest VAR1: intercepted request object.

Servletresponse var2: intercepted response object.

Filterchain var3: filter chain. It provides the dofilter () method to release the filter.

Define filter

[method 1] web.xml configuration

public class FilterDemo1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("FilterDemo1.init");
    }
    @Override
    public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException,ServletException {
        System.out.println("FilterDemo1.doFilter");
    }
    @Override
    public void destroy() {
        System.out.println("FilterDemo1.destroy");
    }
}
    <filter>
        <filter-name>Filter1</filter-name>
        <filter-class>com.my.filter.FilterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/*</url-pattern><!--拦截路径/*表示拦截所有资源-->
    </filter-mapping>

[mode 2] annotation configuration

@WebFilter("/*")
public class FilterDemo1 implements Filter

life cycle

When the web application is loaded into the container, the filter object is created and initialized by the init method.

After the filter object is created, it always exists in memory. The dofilter method is executed every time a request or response is intercepted.

After the dofilter method is executed, you can choose to release the processing results. The processing logic depends on the specific situation.

The filter object will not be destroyed until the web application is removed from the container, and the destroy method will be executed before destruction.

Configuration details

[intercept path configuration]:

[interception mode configuration]:

Annotation: set the dispatchertypes attribute, such as @ webfilter (value = "/ filterdemo4", dispatchertypes = dispatchertype. Request).

web. XML configuration

Filter chain

Execution process

Execution sequence

[annotation configuration]

The filter sequence is compared according to the string comparison rules of the class name. Those with small values are executed first, and filter1 is executed before Filter2.

[web. XML] configuration

The filter order is determined by the configuration order of < filter mapping >, and those configured first are intercepted first.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>