Javaweb Learning Summary (42)--filter (filter) Learning

Source: Internet
Author: User

Javaweb Learning Summary (42)--filter (filter) Learn one, filter introduction

Filter, also known as filters, is the most exciting 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.
The Servlet API provides a filter interface that, when developing a Web application, if the Java class is written to implement this interface, the Java class is called filter filter. Filter technology enables developers to intercept requests and responses to access before a user accesses a target resource, as follows:

  

Second, how does the filter achieve interception?

The filter interface has a Dofilter method that, when we write the filter and configure 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, so Writing code within this method can achieve the following purposes:

    1. Let a piece of code execute before invoking the target resource.
    2. Whether to invoke 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, 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.

Iii. Introduction to filter development 3.1, filter development steps

The filter development is divided into two steps:

    1. Write the 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 filter class that was written and set the resources it can intercept.

  Filter Example:

 1 package me.gacl.web.filter; 2 3 Import java.io.IOException; 4 5 Import Javax.servlet.Filter; 6 Import Javax.servlet.FilterChain; 7 Import Javax.servlet.FilterConfig; 8 Import javax.servlet.ServletException; 9 Import javax.servlet.servletrequest;10 Import javax.servlet.servletresponse;11/**13 * @ClassName: FilterDemo0114 *                        @Description: Three typical applications for filter: 15 * 1, you can decide whether to invoke the Chain.dofilter (request, Response) method in the filter, 16 * That is, if the target resource executes 17 * 2, before the target resource executes, the request\response can be preprocessed before the target resource executes 18 * 3 , after the target resource executes, it can capture the result of the target resource's execution, and realize some special functions. * @author: Aloof Wolf * @date: 2014-8-31 PM 10:09:2421 */public class FilterDemo01 I         Mplements Filter {@Override25 public void init (Filterconfig filterconfig) throws Servletexception {26 System.out.println ("----filter Initialization----")}28 @Override30 public void DoFilter (ServletRequest request, Serv Letresponse response,31 filterchain chain) thRows IOException, Servletexception {32 33//For some preprocessing of request and response Request.setcharacterencodin G ("UTF-8"); Response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8") ; System.out.println ("FilterDemo01 before!!!  "); Chain.dofilter (request, response); Let the target resources execute, release the System.out.println ("FilterDemo01 after the execution!!!" ");}42 @Override44 public void Destroy () {System.out.println ("----Filter Destruction----"); 46}47}

On the web. Configure filters in XML:

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app version= "3.0" 3 xmlns= "http://java.sun.com/xml/ns/ Java EE "4 xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "5 xsi:schemalocation=" Http://java.sun.com/xml/ns   /javaee 6 Http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "> 7 <display-name></display-name> 8    <welcome-file-list> 9 <welcome-file>index.jsp</welcome-file>10 </welcome-file-list>11 12 <!--configuration filter-->13 <filter>14 <filter-name>filterdemo01</filter-name>15 <filter-cl Ass>me.gacl.web.filter.filterdemo01</filter-class>16 </filter>17 <!--map filter-->19 <filter -mapping>20 <filter-name>filterdemo01</filter-name>21 <!--"/*" means to intercept all requests-->22 <u rl-pattern>/*</url-pattern>23 </filter-mapping>24 </web-app> 
3.2. 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.

Iv. life cycle of filter 4.1, creation of filter

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 invokes its Init method, completing the initialization of the object to prepare for interception of subsequent user requests. The filter object is created only once, and the Init method is executed only once . The Filterconfig object representing the current filter configuration information can be obtained through 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 you configure the 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. As a result, when writing the filter, the developer can obtain: 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 name specified 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.
Example: Using Filterconfig to get filter configuration information

 1 package me.gacl.web.filter; 2 3 Import java.io.IOException; 4 Import java.util.Enumeration; 5 Import Javax.servlet.Filter; 6 Import Javax.servlet.FilterChain; 7 Import Javax.servlet.FilterConfig; 8 Import javax.servlet.ServletException; 9 Import javax.servlet.servletrequest;10 Import javax.servlet.servletresponse;11 public class FilterDemo02     Implements filter {13 14/* Filters initialized with * @see Javax.servlet.filter#init (javax.servlet.FilterConfig) 16 */17 @Override18 public void init (Filterconfig filterconfig) throws Servletexception {System.out.println ("----over Filter initialization----");/**21 * <filter>22 <filter-name>filterdemo02</filter-nam e>23 <filter-class>me.gacl.web.filter.filterdemo02</filter-class>24 &lt ;! --Configure the initialization parameters of the FilterDemo02 filter-->25 <init-param>26 <description> config filter Initialization parameters of the DEMO02 filter </description>27                       <param-name>name</param-name>28 <param-value>gacl</param -value>29 </init-param>30 <init-param>31 <desc                        Ription> Configuring the initialization parameters of the FilterDemo02 filter </description>32 <param-name>like</param-name>33 <param-value>java</param-value>34 </init-param>35 & lt;/filter>36 Notoginseng <filter-mapping>38 <filter-name>filterdemo02&lt ;/filter-name>39 <!--"/*" means to intercept all requests-->40 <url-pattern>/*</url-patter n>41 </filter-mapping>42 */43//Get filter name of the String filtername = Filterconfig          . Getfiltername (); 45//Get initialization parameters configured in the Web. xml file INITPARAM1 = Filterconfig.getinitparameter ("name"); 47 String InitparaM2 = Filterconfig.getinitparameter ("like"); 48//Returns an enumeration collection of the names of all initialization parameters of the filter. enumeration<string> initparameternames = Filterconfig.getinitparameternames (); Syste M.out.println (FilterName); System.out.println (initParam1); System.out.println (INITPARAM2); Hile (Initparameternames.hasmoreelements ()) {string paramname = (String) initparameternames.nextelement (); 5 6 System.out.println (paramname),}58}59 @Override61 public void DoFilter (servletrequ EST request, Servletresponse response,62 Filterchain chain) throws IOException, servletexception {S Ystem.out.println ("FilterDemo02 before the execution!!!  "); Chain.dofilter (request, response); Let the target resources execute, release the System.out.println ("FilterDemo02 after the execution!!!" ");}67 @Override69 public void Destroy () {System.out.println ("----Filter Destruction----"); 71}72}
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 has been developed, it needs to be registered in the Web. xml file, so that it can be called

Register the filter example in the Web. xml file:

1 <filter> 2           <description>filterdemo02 filter </description> 3           <filter-name> Filterdemo02</filter-name> 4           <filter-class>me.gacl.web.filter.FilterDemo02</filter-class> 5           <!--configuration FilterDemo02 Filter Initialization Parameters--6           <init-param> 7               <description> Configure initialization parameters for FILTERDEMO02 filters </description> 8               <param-name>name</param-name> 9               < param-value>gacl</param-value>10           </init-param>11           <init-param>12               < Description> Configuring the initialization parameters of the FilterDemo02 filter </description>13               <param-name>like</param-name>14               <param-value>java</param-value>15           </init-param>16 </filter>

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

<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. If the filter does not need to specify initialization parameters, then the <init-param> element may not be configured.

5.2. Map Filter

After registering the filter in the Web. xml file, also map the filter in the Web. xml file

1  <!--map filter-->2   <filter-mapping>3       <filter-name>filterdemo02</filter-name>4       <!--"/*" means to intercept all requests-->5       <url-pattern>/*</url-pattern>6   </filter-mapping>

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. As follows:

1 <filter-mapping>2     <filter-name>testfilter</filter-name>3    <url-pattern>/ Index.jsp</url-pattern>4    <dispatcher>request</dispatcher>5    <dispatcher>FORWARD </dispatcher>6 </filter-mapping>

<dispatcher> the values that child elements can set and their meanings:

    1. 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.
    2. INCLUDE: The filter will be called if the target resource is accessed through the RequestDispatcher include () method. In addition, the filter is not called.
    3. 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.
    4. 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.

Javaweb Learning Summary (42)--filter (filter) Learning

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.