Create and configure a filter

Source: Internet
Author: User

Two steps are required to create a filter:

    1. Create a filter processing class.
    2. Configure filter in the web. xml file.

Create filter class

To create a filter, you must implement the javax. servlet. Filter interface, which defines the following three methods:

    • Void Init (filterconfig config); used to initialize the filter.
    • Void destroy (); used to recycle certain resources before the filter is destroyed.
    • Void dofilter (servletrequest request, servletresponse response, filterchain chain); implements the filter function and adds additional processing for each request and response.

The following is a sample log filter code that intercepts all user requests and records the request information in the log.

@WebFilter(filterName="log",urlPatterns={"/*"})public class LogFilter implements Filter{    //FilterConfig可用于访问Filter的配置信息    private FilterConfig config;    //实现初始化方法    public void init(FilterConfig config)    {        this.config = config;    }    //实现销毁方法    public void destroy()    {        this.config = null;    }    //执行过滤的核心方法    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException,ServletException    {        //-----------下面代码用于对用户请求执行预处理---------------        //获取ServletContext对象,用于记录日志        ServletContext context = this.config.getServletContext();        long before = System.currentTimMillis();        System.out.println("开始过滤.......");        //将请求转换成HttpServletRequest请求        HttpServletRequest hrequest = (HttpServletRequest)request;        //输出提示信息        System.out.println("Filter已将接货到用户的请求的地址:"+hrequest.getServletPath());        //Filter只是链式处理,请求依然方形到目的地址        chain.doFilter(request,response);//预处理与后处理的分界线        //---------------下面代码用于对服务器响应执行后处理-----------        long after = System.currentTimeMillis();        //输出提示信息        System.out.println("过滤结束");        //输出提示信息        System.out.println("请求被定位到" + hrequest.getRequestURI() + " 所花的时间为:" + (after-before));   }}

In the above request filter, only the request URL is recorded in the log, and the chain. dofilter method is executed for all requests. After the filter filters the requests, the request is still sent to the destination address. If you need to check the permission, you can determine whether the user permission is sufficient Based on the http session requested by the user in the filter. If not, you can directly call redirection without calling the chain. dofilter method.

Configure Filter

To configure the filter and Servlet, you must configure the following two parts:

    • Configure the Filter Name.
    • Configure the filter interception URL mode.

The difference is that the URL mode of the filter usually uses the mode string, so that the filter can intercept multiple requests. Similar to configuring servlet, you can configure filter in the following two ways:

    • Configure the filter class through annotation.
    • Configure the file in the web. xml file.

@ Webfilter: modifies a filter class to configure the filter. It supports common attributes shown in the following table.

Attribute Required Description
Asyncsupported No Specifies whether the filter supports asynchronous operation mode.
Dispatchertypes No Specify that the filter only filters requests in the dispatcher mode. This attribute supports any combination of the five values async, error, forward, include, and request, the default value is to filter requests in the 5 medium mode by colleagues.
Displayname No Display name of the filter
Filtername No Specify the Filter Name
Initparams No Used to configure parameters for the filter
Servletnames No This attribute value can be used to specify the names of multiple servlets. It is used to specify that the filter only filters these servlets.
Urlpatterns/value No

The two attributes share the same role and specify the URL intercepted by the filter.

 

 

 

 

 

 

 

The configuration of filter in the web. xml file is similar to the configuration of servlet. You need to specify the URL it filters for the filter, and you can configure parameters.

Add the following configuration snippet to the filter in the web. xml file:

<!-- 定义Filter --><filter>    <!-- Filter的名字,相当与指定@WebFilter的filterName属性 -->    <filter-name>log</filter-name>    <!-- Filter的实现类 -->    <filter-class>luxl.LogFilter</filter-class><filter><!-- 定义Filter拦截的URL地址 --><filter-mapping>    <!-- Filter的名字 -->    <filter-name>log</filter-name>    <!-- Filter负责拦截的URL,相当于指定@WebFIlter的urlPatterns属性 -->    <url-pattern>/*</url-pattern></filter-mapping>

In actual projects, the code in the dofilter () method in the filter is the common code extracted from the Service () Methods of multiple servlets. By using the filter method, the code can be used for better code reuse.

Filter can also configure initialization parameters through the <init-Param.../> element or the initparams attribute of @ webfilter. To obtain the filter initialization parameters, use the getinitparameter () method of filterconfig.

Create and configure a filter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.