Java Web Filter Filter Learning Tutorial (recommended) _java

Source: Internet
Author: User
Tags java web

Introduction of Filter

Filter is also called filters, it is the most exciting technology in the 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, 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.

The Servlet API provides a filter interface that, when developing a Web application, is called filter filter if the Java class that is written implements the interface. With the filter technology, developers can enable users to intercept requests and responses to access before accessing a target resource, as follows:

Second, how is the filter to achieve interception?

There is a Dofilter method in the filter interface, and when we write the filter and configure which Web resource to intercept, the Web server calls the filter's Dofilter method every time before invoking the service method of the Web resource, so Writing code within the method can accomplish 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).

3. After invoking the target resource, let a piece of code execute.

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.

Introduction to the development of filter

3.1. Filter development steps

Filter development is divided into two steps:

1. Write Java class to implement the filter interface and implement its Dofilter method.

2. Use the <filter> and <filter-mapping> elements in the Web.xml file to register the written filter class and set the resources it can intercept.

 Filter Example:

Package me.gacl.web.filter;
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;
/** * @ClassName: Filterdemo * @Description: Three typical applications of filter: *, you can decide whether to call Chain.dofilter (request, Response) method in filter according to the condition, * Whether to let the target resource execute *, before letting the target resource execute, can preprocess the request\response, then let the target resource execute *, after the target resource executes, can capture the result of the target resource execution, thus realize some special function * @author: Aloof Wolf  Date:--pm:: */public class Filterdemo implements Filter {@Override public void init (Filterconfig filterconfig) throws servletexception {System.out.println ("----filter Initialization----"); @Override public void Dofilter (ServletRequest request,
Servletresponse response, Filterchain chain) throws IOException, Servletexception {//preprocessing of request and response
Request.setcharacterencoding ("utf-");
Response.setcharacterencoding ("utf-");
Response.setcontenttype ("text/html;charset=utf-"); System.out.println("Filterdemo!!! before execution.
"); Chain.dofilter (request, response); Let the target resources execute, Release System.out.println ("Filterdemo after execution!!!
");
}  @Override public void Destroy () {System.out.println ("----filter Destroy----");}

  On the web. Configure filters in XML:

<?xml version= "." Encoding= "utf-"?> <web-app
". 
" xmlns= "Http://java.sun.com/xml/ns/javaee" 
xmlns:xsi= "Http://www.w.org//XMLSchema-instance" 
xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app__.xsd" >
<display-name></display-name> 
<welcome-file-list>
<welcome-file>index.jsp </welcome-file>
</welcome-file-list>
<!--configuration filter-->
<filter>
< Filter-name>filterdemo</filter-name>
<filter-class>me.gacl.web.filter.filterdemo</ filter-class>
</filter>
<!--mapping filter-->
<filter-mapping>
<filter-name >FilterDemo</filter-name>
<!--"/*" means to intercept all requests-->
<url-pattern>/*</url-pattern >
</filter-mapping>

3.2. 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 the filter is registered in the Web.xml file, and when the Dofilter method of the first filter 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.

Iv. the life cycle of the filter

4.1, the creation of filter

The creation and destruction of the filter is the responsibility of the Web server. When a Web application starts, the Web server creates an instance object of the filter and invokes its Init method to complete the initialization of the object, which prepares the filter object to be blocked for subsequent user requests, only once, and only once for the Init method. The Filterconfig object representing the current filter configuration information can be obtained by using the parameters of the Init method.

4.2, the destruction of filter

The Web container calls the Destroy method to destroy the filter. The Destroy method executes only once in the life cycle of the filter. In the Destroy method, you can release the resources used by the filter.

4.3, Filterconfig interface

When the user configures filter, you can use <init-param> to configure some initialization parameters for the filter, 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, by filterconfig the object's method, it is available:

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 (): An enumeration collection that returns the names of all initialization parameters for a filter.

Public ServletContext Getservletcontext (): Returns a reference to the Servlet context object.

Example: Using Filterconfig to get filter configuration information

Package me.gacl.web.filter;
Import java.io.IOException;
Import java.util.Enumeration;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse; public class Filterdemo implements filter {/* Filter initialization * @see Javax.servlet.filter#init (javax.servlet.FilterConfig) * * * @Ove Rride public void init (Filterconfig filterconfig) throws Servletexception {System.out.println ("----filter Initialization----");/** * & Lt;filter> <filter-name>FilterDemo</filter-name> <filter-class> Me.gacl.web.filter.filterdemo</filter-class> <!--Configure initialization parameters for Filterdemo filters--> <init-param> < Description> Configuration Filterdemo Filter Initialization parameters </description> <param-name>name</param-name> < param-value>gacl</param-value> </init-param> <init-param> <description> Configure initialization parameters for Filterdemo filters </description> <param-name>like</param-name> <param-value>java</param-value> </init-param> </filter> < Filter-mapping> <filter-name>FilterDemo</filter-name> <!--"/*" means to intercept all requests--> <url-pattern
>/*</url-pattern> </filter-mapping> *//Get filter name String filtername = Filterconfig.getfiltername ();
Gets the initialization parameter String Initparam = Filterconfig.getinitparameter ("name") configured in the Web.xml file;
String Initparam = Filterconfig.getinitparameter ("like");
Returns an enumeration collection of the names of all initialization parameters for the filter.
enumeration<string> initparameternames = Filterconfig.getinitparameternames ();
System.out.println (FilterName);
System.out.println (Initparam);
System.out.println (Initparam);
while (Initparameternames.hasmoreelements ()) {String paramname = (string) initparameternames.nextelement ();
System.out.println (paramname); @Override public void Dofilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException , servletexception {System.out.println ("Filterdemo before execution!!!
"); ChAin.dofilter (request, response); Let the target resources execute, Release System.out.println ("Filterdemo after execution!!!
");
} @Override public void Destroy () {System.out.println ("----filter Destroy----");}

V. Deployment of the Filter

The deployment of filter is divided into two steps:

1. Register Filter

2. Map Filter

5.1. Register Filter

After the filter is developed, it needs to be registered in the Web.xml file so that it can be invoked by the Web server

Register the filter example in the Web.xml file:

<filter>
<description>filterdemo filter </description>
<filter-name>filterdemo</ filter-name>
<filter-class>me.gacl.web.filter.FilterDemo</filter-class>
<!-- Configure initialization parameters for Filterdemo filters-->
<init-param>
<description> Configure initialization parameters for Filterdemo filters </ description>
<param-name>name</param-name>
<param-value>gacl</param-value>
</init-param>
<init-param>
<description> Configure initialization parameters for Filterdemo filters </description >
<param-name>like</param-name>
<param-value>java</param-value>
< /init-param>

<description> for adding descriptive information, the content of the element can be empty,<description> can not be configured.

<filter-name> to specify a name for the filter, the contents of the element cannot be empty.

The <filter-class> element is used to specify the complete qualified class name for the filter.

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. In a filter, you can use the Filterconfig interface object to access initialization parameters. If the filter does not need to specify initialization parameters, then the <init-param> element may not be configured.

5.2. Map Filter

After the filter is registered in the Web.xml file, the filter is also mapped in the Web.xml file

<!--mapping filter-->
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<!- -"/*" means to intercept all requests-->
<url-pattern>/*</url-pattern>

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

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 (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

Filter intercepts multiple invocation modes of a resource. As follows:

<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/index.jsp </url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>forward</ Dispatcher>

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

1.REQUEST: When the user accesses the page directly, the Web container will invoke the filter. 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 will be 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.

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.