Java Filter Filter Detailed introduction and instance code _java

Source: Internet
Author: User
Tags character set wrapper

Introduction to Filter

Filter, also known as filters, is the most useful 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 to intercept, In order to realize some special functions. such as 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, and to HttpServletResponse. The full process of using filter: Filter preprocessing the user request, then handing the request to the servlet for processing and generating a response, and finally filter to the server response after processing.

Filter function

1. Intercept the customer's httpservletrequest before HttpServletRequest arrives in the Servlet. Check httpservletrequest as needed, or modify httpservletrequest headers and data.

2. Intercept HttpServletResponse before HttpServletResponse arrives at the client. Check httpservletresponse as needed, or modify HttpServletResponse headers and data.

How to use filter to realize 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 each time before invoking the service method of the Web resource, Therefore, writing code within the method can achieve the following purposes:

1. Let a piece of code execute before invoking the target resource.

2. Whether to call the target resource (that is, whether to let the user access the Web resource).

When the Web server calls the Dofilter method, it passes a Filterchain object that 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, and the method is invoked, and the Web server invokes the service method of the Web resource, that is, the Web resource is accessed, otherwise the web resource is not accessed.

Two steps to develop filter

The Java class is written to implement the filter interface and implement its Dofilter method.
Use and element to register the filter class written in the Web.xml file and set the resources it can intercept.
Web.xml configuration of each node description:

    1. <filter> Specify a filter.
    2. <filter-name> to specify a name for the filter, the contents of the element cannot be empty.
    3. The <filter-class> element is used to specify the complete qualified class name for the filter.
    4. The <init-param> element is used to specify the initialization parameter for the filter, its child element <param-name> the name of the specified parameter,<param-value> the value of the specified parameter.
    5. In a filter, you can use the Filterconfig interface object to access initialization parameters.

The <filter-mapping> element is used to set a resource that the filter is responsible for intercepting. A filter-blocking resource can be specified in two ways: the Servlet name and the request path for resource access

    1. 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
    2. <url-pattern> set the request path blocked by filter (filter associated URL style)

<servlet-name> Specifies the servlet name that the filter intercepts.

<dispatcher> specifies how the resource intercepted by the filter is invoked by the Servlet container, which can be one of Request,include,forward and error, and the default request. Users can set multiple <dispatcher> child elements to specify how the Filter will intercept multiple calls to the resource.

The value that the <dispatcher> child element can set and its meaning

    1. REQUEST: The Web container will invoke the filter when the user accesses the page directly. If the target resource is accessed through the requestdispatcher include () or forward () method, then the filter is not invoked.
    2. Include: If the target resource is accessed through the RequestDispatcher include () method, the filter is invoked. In addition, the filter is not invoked.
    3. FORWARD: If the target resource is accessed through the RequestDispatcher FORWARD () method, then the filter will be invoked, and the filter will not be invoked.
    4. ERROR: If the target resource is invoked through a declarative exception handling mechanism, the filter is invoked. In addition, filters are not invoked.

Filter Chain

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

The Web server decides which filter to call first, based on the order in which filter is registered in the Web.xml file, and when the first filter's Dofilter method is invoked, The Web server creates a Filterchain object that represents the filter chain to pass 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 any filter in the Filterchain object, and if so, calls the 2nd filter, if not, The target resource is invoked.

The life cycle of the filter

public void init (Filterconfig filterconfig) throws servletexception;//initialization

Like the servlet program we write, the Web server is responsible for the creation and destruction of the filter. When the Web application starts, the Web server creates an instance object of the filter and invokes its Init method. Reads the Web.xml configuration, completes the initialization of the object, and prepares the interception for subsequent user requests (the filter object will only be created once and the Init method will only execute once). The developer uses the parameters of the Init method to obtain the Filterconfig object that represents the current filter configuration information.

public void Dofilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception;//Intercept Request

This method completes the actual filtering operation. When a client 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

The filter object, when created, resides in memory and is destroyed when the Web application is removed or the server stops. 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 a user configures filter, you can configure some initialization parameters for filter by passing in the Filterconfig object that encapsulates the filter initialization parameter when the Web container instantiates the filter object and invokes its Init method. As a result, developers can get the following when they write filter by filterconfig the object's method:

String getfiltername ();//Gets the name of the filter. 
string Getinitparameter (string name),//Returns the value of the initialization parameter for the specified 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 for the filter. Public 
ServletContext Getservletcontext ();//Returns a reference to the Servlet context object.

Filter use case

Using filter to authenticate user logon security controls

Some time ago to participate in maintenance of a project, the user quit the system, then go to the Address bar access history, according to the URL, still able to enter the system response page. I'm going to go check it out. Verify that the user logged on without filtering the 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><!--Filter 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 login interface--> <param-value>/index.jsp</param-value> </init-param> <init-param> & lt;param-name>disabletestfilter</param-name><!--Y: Filter Invalid--> <param-value>n</param-value ><!--http://www.manongjc.com/article/1613.html--> </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;

 /** * To determine whether the user is logged in, not logged in to exit the system * http://www.manongjc.com/article/1613.html/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, Servletex ception {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 parameter String redirectpath = Hrequest.getcontextpath () + config.getinitparameter ("Redirectpath");/no landing turn page Stri ng Disabletestfilter = Config.getinitparameter ("Disabletestfilter");//filter is valid if (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 only the specified filter parameter suffix chain.dofilter (request, response);
  Return
   } if (This.iscontains (Hrequest.getrequesturi (), logonlist)) {//No filtering on the login page 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;

 }
}

This can be done to all requests to the user, must pass through this filter to authenticate the user login.

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 time will appear form submission data or upload/download 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><!--is used to specify a specific character set-->
  <param-value>utf-8</ param-value>
 </init-param>
 <init-param>
  <param-name>forceencoding</ param-name><!--true: Whether or not the request specifies a character set, it is encoding;false: If request has specified a character set, 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 the hibernate+spring is in use, if the lazy=true (delay loading) is set, then when reading the data, when the parent data is read, Hibernate automatically closes the session, so that when you want to use the associated data and sub data, The system throws a lazyinit error, and you need to use the Opensessioninviewfilter filter provided by spring.

The main thing is to keep the session state until request sends all the pages to the client until the Opensessioninviewfilter is closed, which resolves the problem of deferred loading.

Note: The Opensessioninviewfilter configuration is to be written in front of the struts2 configuration. Because the Tomcat container is loaded sequentially when the filter is loaded, if the configuration file first writes the STRUTS2 filter configuration and then the Opensessioninviewfilter filter configuration, the order of the loads causes the The action session 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 default. The default is to look for a bean with the ID sessionfactory from the spring container, and if the ID is not sessionfactory, you need to configure the following, where Sessionfactory is the bean in the spring container. -->
  <param-value>sessionFactory</param-value>
 </init-param>
 <init-param >
  <param-name>singleSession</param-name><!--singlesession defaults to True, If set to false it is no use Opensessioninview-->
  <param-value>true</param-value>
 </init-param>
</filter>
<filter-mapping>
 <filter-name>opensessioninviewfilter</ filter-name>
 <url-pattern>*.do</url-pattern>
</filter-mapping>
 

Web.xml Configuration for Struts2

The use of STRUTS2 in the project also requires that the filter be configured in 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. Starting with Struts2.1.3, the Actioncontextcleanup filter is discarded and the corresponding function is included in the Strutsprepareandexecutefilter filter.

Three initialization parameter configurations:

    1. Config parameter: Specifies the configuration file to load. Comma split.
    2. Actionpackages parameter: Specifies the package space in which the action class resides. Comma split.
    3. Configproviders parameter: The custom profile provider 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>

  Thank you for reading, I hope to help you, thank you for your support for this site!

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.