Filter filter in Java

Source: Internet
Author: User

Filter Introduction

Filter, also known as filters, is the most practical technology in Servlet technology, Web developers through the filter technology, Web server management of all Web resources: such as JSP, Servlet, static picture files or static HTML files, etc. to intercept, So that some special functions can be realized. For example, the implementation of URL-level access control, filtering sensitive words, compressed response information and other advanced features.

It is mainly used to preprocess user requests, or to post-process httpservletresponse. Use the full process of filter: Filter to preprocess the user request, then send the request to the servlet for processing and generate a response, and finally filter to post-process the server response.

Filter function

Intercept the client's httpservletrequest before HttpServletRequest arrives at the Servlet. You can also modify the HttpServletRequest header and data as needed to check the httpservletrequest.
Intercept HttpServletResponse before HttpServletResponse arrives at the client. You can also modify the HttpServletResponse header and data as needed to check the httpservletresponse.

How to use filter to implement interception function

The filter interface has a Dofilter method that, when the developer writes the filter and configures which Web resource to intercept, the Web server invokes the filter's Dofilter method every time before invoking the service method of the Web resource. Therefore, writing code within the method can achieve the following purposes:

调用目标资源之前,让一段代码执行。是否调用目标资源(即是否让用户访问web资源)。web服务器在调用doFilter方法时,会传递一个filterChain对象进来,filterChain对象是filter接口中最重要的一个对象,它也提供了一个doFilter方法,开发人员可以根据需求决定是否调用此方法,调用该方法,则web服务器就会调用web资源的service方法,即web资源就会被访问,否则web资源不会被访问。
Filter development Two-step walk

Write the Java class to implement the filter interface and implement its Dofilter method.
Registers the Write filter class in the Web. xml file and sets the resources it can intercept.

The Web. XML Configuration node describes:

<filter> specifies a filter.<Filter-name> is used to specify a name for the filter, and the content of the element cannot be empty.<The filter-class> element is used to specify the full qualified class name of the filter.<The init-param> element is used to specify the initialization parameters for the filter, and its child elements<Param-name> the name of the specified parameter,<Param-value> the value of the specified parameter. In a filter, you can use the Filterconfig interface object to access the initialization parameters.<The filter-mapping> element is used to set a resource that the Filter is responsible for intercepting. A filter interception resource can be specified in two ways: the Servlet name and the request path of the resource access<The filter-name> child element is used to set the registration name of the filter. The value must be in the<The name of the filter declared in the filter> element <url-pattern> Set the request path blocked by filter (the URL style associated with the filter)<  servlet-name> Specifies the name of the servlet that the filter intercepts. <dispatcher> Specifies the way that the resource intercepted by the filter is called by the Servlet container, which can be one of Request,include,forward and error, the default request. The user can set multiple <dispatcher> child elements to specify the Filter to intercept multiple invocation methods of the resource. <dispatcher> The values that child elements can set and their meanings request: The Web container will call the filter when the user accesses the page directly. If the target resource is accessed through the include () or forward () method of RequestDispatcher, then the filter is not called. INCLUDE: The filter will be called if the target resource is accessed through the RequestDispatcher include () method. In addition, the filter is not called. FORWARD: If the target resource is accessed through the RequestDispatcher FORWARD () method, then the filter will be called and the filter will not be called. Error: If the target resource is called through a declarative exception handling mechanism, then the filter will be called. In addition, the filter is not called. 
Filter Chain

In a Web application, you can develop and write multiple filter combinations called the filter chain.

The Web server decides which filter to call first, based on the order in which the filter is registered in the Web. xml file, and when the Dofilter method of the first filter is called, it creates a Filterchain object representing the filter chain that is passed to the method. In the Dofilter method, if the developer calls the Dofilter method of the Filterchain object, the Web server checks to see if there is a filter in the Filterchain object, and if so, the 2nd filter, if not, The target resource is called.

The life cycle of the filter
public voidInitFilterconfig filterconfig)ThrowsServletexception;Initialize and we write theServlet program,Filter is created and destroyed byThe Web server is responsible. When the Web application starts, the Web server createsFilter, and calls the instance object of theThe Init method, which reads the Web. XML configuration, completes the initialization of the object to prepare for interception of subsequent user requests (The filter object is created only once,The Init method is also executed only once). Developers throughThe parameters of the Init method, which can be obtained representing the currentfilter configuration information filterconfig object. public void DoFilter (servletrequest request, servletresponse response, filterchain chain) throws ioexception, ServletException; //intercept Request This method completes the actual filtering operation. When a customer requests access to the url associated with the filter, servlet filter will first execute the Dofilter method. The filterchain parameter is used to access subsequent filters. public void Destroy (); //destroys filter objects that reside in memory after they are created and destroyed when the Web app is removed or the server is stopped. Called before web container unloads filter objects. This method executes only once in the life cycle of the filter. In this method, you can release the resources used by the filter.  
Filterconfig interface

When the user configures the filter, it is possible to configure some initialization parameters for filter, and when the Web container instantiates the filter object and calls its Init method, the Filterconfig object that encapsulates the filter initialization parameter is passed in. So when the developer writes the filter, the Filterconfig object is used to get the following:

String getFilterName();//得到filter的名称。 String getInitParameter(String name);//返回在部署描述中指定名称的初始化参数的值。如果不存在返回null. Enumeration getInitParameterNames();//返回过滤器的所有初始化参数的名字的枚举集合。 public ServletContext getServletContext();//返回Servlet上下文对象的引用。
Filter use case use filter to verify user login security Control

A period of time to participate in the maintenance of a project, after the user exits the system, then go to the Address bar access history, according to the URL, still be able to enter the system response page. I'll check it out. The user is logged on without filtering the authentication request. Add a filter to fix the problem!

First in the Web. XML configuration
<Filter><Filter-name>sessionfilter</Filter-name><Filter-class>com.action.login.sessionfilter</Filter-class><Init-param><Param-name>logonstrings</Param-name><!--do not filter the login page--<Param-value>/project/index.jsp;login.do</Param-value></Init-param><Init-param><Param-name>includestrings</Param-name><!--filters only the specified filter parameter suffix--<param-value>.do;. Jsp</Param-value></Init-param><Init-param><Param-name>redirectpath</Param-name><!--failed to jump to the login screen--<param-value>/index.jsp</Param-value></Init-param><Init-param><Param-name>disabletestfilter</param-name><!--Y: Filter Invalid- <param-value>n</param-value>  </init-param></filter><filter-mapping> <filter-name> Sessionfilter</filter-name> <url-pattern>/*</url-pattern>  </filter-mapping>             
Then write Filterservlet
Package com.action.login;Import java.io.IOException;Import Javax.servlet.Filter;Import Javax.servlet.FilterChain;Import Javax.servlet.FilterConfig;Import javax.servlet.ServletException;Import Javax.servlet.ServletRequest;Import Javax.servlet.ServletResponse;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import Javax.servlet.http.HttpServletResponseWrapper;/** * Determine if the user is logged in, leave the system without logging in */PublicClass SessionfilterImplements Filter {Public Filterconfig config;Publicvoid Destroy () {This.config =Null }PublicStaticBoolean Iscontains (String container,String[] regx) {Boolean result =Falsefor (int i =0; i < regx.length; i++) {if (Container.indexof (regx[i])! =-1) {ReturnTrue } }return result; }Publicvoid DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, Servletexception {HttpServletRequest hrequest = (httpservletrequest) request; Httpservletresponsewrapper wrapper =New Httpservletresponsewrapper ((httpservletresponse) response);String logonstrings = Config.getinitparameter ("Logonstrings");Login Landing PageString includestrings = Config.getinitparameter ("Includestrings");Filter resource suffix parametersString Redirectpath = Hrequest.getcontextpath () + Config.getinitparameter ("Redirectpath");No Landing turn pageString Disabletestfilter = Config.getinitparameter ("Disabletestfilter");Whether the filter is validif (Disabletestfilter.touppercase (). Equals ("Y")) {Filter invalid Chain.dofilter (request, response);Return }string[] Logonlist = Logonstrings.split (";");string[] Includelist = Includestrings.split (";");if (!This.iscontains (Hrequest.getrequesturi (), includelist)) {Filter Chain.dofilter only for the specified filter parameter suffix (request, response);return;} if (this.iscontains (Hrequest.getrequesturi (), logonList)) { //the login page is not filtered chain.dofilter (request, response); return;} string user = (string) hrequest.getsession (). GetAttribute (  "useronly"); //determine whether the user is logged in if (user = = null) { Wrapper.sendredirect (Redirectpath); return;} else {chain.dofilter (request, response); return;} } public void init (Filterconfig filterconfig) throws servletexception {config = filterconfig;}}            

In this way, all requests to the user are completed and the user is authenticated by this filter.

Prevent Chinese garbled filter

When the project uses the Spring framework. The current JSP page and Java code in the use of different character sets to encode the data will appear when the form submitted or upload/download the Chinese name file garbled problem, then you can use this filter.

<Filter><Filter-name>encoding</Filter-name><Filter-class>org.springframework.web.filter.characterencodingfilter</Filter-class><Init-param><Param-name>encoding</Param-name><!--used to specify a specific character set--<Param-value>utf-8</Param-value></Init-param><Init-param><Param-name>forceencoding</param-name><!--true: Regardless of whether the request specifies a character set, the encoding False: If request has a character set specified, do not use encoding--> <param-value> False</param-value> </init-param></filter> <filter-mapping> < filter-name>encoding</filter-name > <url-pattern>/*</url-pattern></FILTER-MAPPING>   

Filter filter in Java

Related Article

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.