The filter filter in Java is detailed

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:

Let a piece of code execute before invoking the target resource.
Whether to invoke the target resource (that is, whether to let the user access the Web resource).
When the Web server calls the Dofilter method, a Filterchain object is passed in, and the Filterchain object is the most important object in the filter interface, and it also provides a Dofilter method. The developer can decide whether to call this method on demand or not, and the Web server invokes the Web resource's service method, which means that the Web resource will be accessed or the Web resource will not be accessed.

Filter development Two-step walk

Write the Java class to implement the filter interface and implement its Dofilter method.
Use the and element to register the filter class written in the Web. xml file and set the resources it can intercept.
The Web. XML Configuration node describes:

<filter> Specify 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, 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 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 how the resource that the filter intercepts is called by the Servlet container, which can be one of Request,include,forward and error, the default request. Users can set multiple <dispatcher> child elements to specify the Filter to intercept multiple calls to the resource.
<dispatcher> the values that child elements can set and their meanings
REQUEST: When the user accesses the page directly, the Web container invokes the filter. 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 void init (Filterconfig filterconfig) throws servletexception;//initialization
Like the servlet program we wrote, the creation and destruction of the filter is the responsibility of the Web server. When the Web application starts, the Web server creates an instance object of filter and calls its Init method, Read the Web. XML configuration and complete the initialization of the object to prepare for interception of subsequent user requests (the filter object is created only once, and the Init method executes only once). The Filterconfig object that represents the current filter configuration information is available to the developer through the parameters of the Init method.

public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception;//interception Request
This method completes the actual filtering operation. When a customer requests access to the URL associated with the filter, the servlet filter executes the Dofilter method first. The Filterchain parameter is used to access subsequent filters.

public void Destroy ();//Destroy
When the filter object is created, it resides in memory and is destroyed when the Web app is removed or the server is stopped. Called before the Web container unloads the Filter object. 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 ();//Gets the name of the filter.
String Getinitparameter (string name);//Returns the value of the initialization parameter that specifies the name in the deployment description. Returns null if it does not exist.
Enumeration Getinitparameternames ();//Returns an enumeration collection of the names of all initialization parameters of the filter.
Public ServletContext getservletcontext ();//Returns a reference to the Servlet context object.
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 is 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.java:

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 or not logged in and exit the system
*/
public class Sessionfilter implements Filter {

Public Filterconfig config;

public void Destroy () {
This.config = null;
}

public static Boolean iscontains (String container, string[] regx) {
Boolean result = false;
for (int i = 0; i < regx.length; i++) {
if (Container.indexof (regx[i])! =-1) {
return true;
}
}
return result;
}
public void 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 Page
String includestrings = Config.getinitparameter ("includestrings"); Filter resource suffix parameters
String Redirectpath = Hrequest.getcontextpath () + config.getinitparameter ("Redirectpath");//no Landing Steering page
String Disabletestfilter = Config.getinitparameter ("Disabletestfilter");//filter is valid

if (Disabletestfilter.touppercase (). Equals ("Y")) {//filter not valid
Chain.dofilter (request, response);
Return
}
string[] Logonlist = Logonstrings.split (";");
string[] Includelist = Includestrings.split (";");

if (!this.iscontains (Hrequest.getrequesturi (), includelist)) {//filter only the specified filter parameter suffix
Chain.dofilter (request, response);
Return
}

if (This.iscontains (Hrequest.getrequesturi (), logonlist)) {//Do not filter the login page
Chain.dofilter (request, response);
Return
}

String user = (string) hrequest.getsession (). getattribute ("useronly");//Determine if 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: encoding is used regardless of whether the request has a character set specified False: If request has a character set specified, the encoding--> is not used
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Spring+hibernate's Opensessioninviewfilter control session switch

When hibernate+spring is used, if lazy=true is set (lazy loading), Suzhou Lou Feng Then when reading the data, hibernate will automatically close the session when the parent data is read, so that When you want to use the associated data, sub-data, the system will throw lazyinit errors, then you need to use the spring provided by the Opensessioninviewfilter filter.

The opensessioninviewfilter is to keep the session state until the request sends all the pages to the client, until the session is closed, so that the problem of lazy loading can be resolved.

Note: The Opensessioninviewfilter configuration is to be written in front of the struts2 configuration. Because the Tomcat container is loaded in order when the filter is loaded, if the configuration file first writes the STRUTS2 filter configuration and then the Opensessioninviewfilter filter configuration, the order of loading is caused, The action is not managed by spring when it obtains data.

<filter><!--lazy loading enabled in spring-->
<filter-name>opensessioninviewfilter</ Filter-name>
<filter-class>org.springframework.orm.hibernate3.support.opensessioninviewfilter</ Filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name><!-- can be defaulted. The default is to find the bean with the ID sessionfactory from the spring container, and if the ID is not sessionfactory, it needs to be configured as follows, where Sessionfactory is the bean in the spring container. -->
<param-value>sessionfactory</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name><!--singlesession default to True, If set to false it is useless opensessioninview-->
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Struts2 's web. XML configuration

Using STRUTS2 in the project also requires a filter in the Web. XML to intercept the request and go to the Struts2 action for processing.

Note: If the previous Struts2 version of 2.1.3, the filter uses Org.apache.struts2.dispatcher.FilterDispatcher. Otherwise, use Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter. Suzhou Lou Feng www.jsgren.com/forum-43-1.html from Struts2.1.3, the Actioncontextcleanup filter is discarded, and the Strutsprepareandexecutefilter filter contains the corresponding functions.

Configuration of three initialization parameters:

Config parameter: Specifies the configuration file to load. Comma split.
Actionpackages parameter: Specifies the package space where the action class resides. Comma split.
Configproviders parameter: A custom profile provider that needs to implement the Configurationprovider interface class. Comma split.
<!--struts 2.x filter--
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>

The filter filter in Java is detailed

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.