Java Servlet Filter

Source: Internet
Author: User
Tags apache tomcat

Do Web development for the filter should not be unfamiliar, has been very simple to use, but there has been no systematic summary, with the age of slowly growing up, like to summarize some things, the following say I understand the filter, the official definition of filter is A plug-in that performs a filtering operation when requesting a resource or returning information from a resource. we use the most filtered scenarios to estimate the character set conversion at the time of request and return, or permission control, such as a user not logged in cannot request some resources. Here's a look at the set type of filter:

    • Authentication Filters
    • Logging and Auditing Filters
    • Image Conversion Filters
    • Data Compression Filters
    • Encryption Filters
    • Tokenizing Filters
    • Filters that trigger resource access events
    • xsl/t Filters
    • Mime-type chain Filter

Filters is a plug-in configured in Web. XML, Servlets and filters are not dependent on each other if filters are added and removed by editing web. Xml.

Implementation of the filter is very simple, just to implement the Javax.servlet.Filter interface, you can implement a filter, the filter interface defines the method as follows:

    • void init (Filterconfig filterconfig))--called by container when the filter is loaded into the service, Servlet Container the Init method of filter is called immediately after the filter is instantiated, the work in the Init method must be completed correctly before the filter filtering task is performed.

The Web container cannot load the filter into the service under the following circumstances:

      • Throws a Servletexception exception.
      • Not returned within the time defined by container.
    • void DoFilter (ServletRequest request, servletresponse response, Filterchain chain)--filter method at each DoFilter Response is called by container and can be passed to the request in Dofilter or response to the next link in the filter ring. The filter in this case is called the responsibility chain pattern structure in design mode, This is the role of the abstract processor is javax.servlet.Filter this interface, registered all filter is a specific processor, in the Dofilter method to implement the specific processing logic, where the responsibility chain is a straight line, which constitutes this line is all registered filter.
    • destroy--when filter is removed from the service, container calls the Destroy method, releasing the system resources that the filter occupies by invoking this method.

How to configure filter in Web. xml

1 <filter>2     <display-name>ecodingfilter</display-name>3     <filter-name> Ecodingfilter</filter-name>4     <filter-class>org.nb.filter.encodefilter</filter-class>5     <init-param>6         <param-name>encodecoding</param-name>7         <param-value>utf-8 </param-value>8     </init-param>9 </filter>

We can use the following method to match the filter to the specified servlet resource or Url-pattern:

1 <filter-mapping>2     <filter-name>ecodingfilter</filter-name>3     <servlet-name>* </servlet-name>4     <url-pattern>*</url-pattern>5 </filter-mapping>

It is important to note here that when registering the filter ring with the servlet, container first deals with the url-patterns and then processes the servlet-names, so if there is a requirement for the execution order of the filter, you need to be aware of this. Let's create a Web project to practice the filter:

Web. XML content:

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 3 Xmlns= "Http://java.sun.com/xml/ns/javaee" 4 xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "5 version=" 3.0 "> 6 <display-name>filtertest</display-name& Gt 7 <welcome-file-list> 8 <welcome-file>index.html</welcome-file> 9 </welcome-file-list >10 <filter>11 <display-name>ecodingfilter</display-name>12 <filter-name>Ec Odingfilter</filter-name>13 <filter-class>org.nb.filter.encodefilter</filter-class>14 &L T;init-param>15 <param-name>encodecoding</param-name>16 <param-value>utf-8&lt ;/param-value>17 </init-param>18 </filter>19 <filter-mapping>20 <filter-na Me>ecodingfilter</filter-naMe>21 <servlet-name>hello</servlet-name>22 <url-pattern>*</url-pattern>23 & lt;/filter-mapping>24 <servlet>25 <servlet-name>hello</servlet-name>26 <servle t-class></servlet-class>27 </servlet>28 <servlet-mapping>29 <servlet-name>hello </servlet-name>30 <url-pattern>/*</url-pattern>31 </servlet-mapping>32 </web-app&gt ;

Helloservlet.java content:

1 package org.nb.action; 2  3 import java.io.IOException; 4 import java.io.PrintWriter; 5  6 import javax.servlet.ServletException; 7 Import Javax.servlet.annotation.WebServlet; 8 Import Javax.servlet.http.HttpServlet; 9 Import javax.servlet.http.httpservletrequest;10 Import javax.servlet.http.httpservletresponse;11 @WebServlet ("/ HelloServlet ") public class HelloServlet extends HttpServlet {$     private static final long Serialversionuid = 1l;15     protected void DoPost (HttpServletRequest request,17             httpservletresponse response) throws Servletexception , IOException {         printwriter out = Response.getwriter ();         out.println ("<font color=red>hello.</ Font> ");     }21}

ENCODEFILTER.XM content:

 1 package org.nb.filter; 2 3 Import java.io.IOException; 4 Import java.util.Enumeration; 5 Import Java.util.HashMap; 6 Import Java.util.Map; 7 8 Import Javax.servlet.Filter; 9 Import javax.servlet.filterchain;10 Import javax.servlet.filterconfig;11 import javax.servlet.servletexception;12 Import javax.servlet.servletrequest;13 Import javax.servlet.servletresponse;14 public class Encodefilter implements Filter {map<string, string> params = new hashmap<string, string> (); @Override20 public void Destroy () {System.out.println ("encodefilter Destroy");}23 @Override25 public void dofilt  ER (servletrequest request, Servletresponse response,26 Filterchain chain) throws IOException, Servletexception         {String encodecoding = params.get ("encodecoding"); request.setcharacterencoding (encodecoding); 29    Response.setcharacterencoding (encodecoding); Chain.dofilter (request, response); 31     System.out.println ("Encodefilter doFilter");}33 @Override35 public void init (filterconfig cfg) thro WS Servletexception {enumeration<string> names = Cfg.getinitparameternames (); PNs while (names.hasm Oreelements ()) {$ String name = Names.nextelement (); Params.put (name, Cfg.getinitparameter (name );}41 System.out.println ("Encodefilter init"); 42}43 44}

What the console outputs when Tomcat starts:

March 24, 2014 5:56:12 pm org.apache.catalina.core.AprLifecycleListener init info: The APR based Apache Tomcat Native library WH Ich allows optimal performance in production environments is not found on the Java.library.path:e:\program FILES\JAVA\JR E7\bin; C:\Windows\Sun\Java\bin; C:\Windows\system32; C:\Windows; C:\Program Files (x86) \m1 Licensing; C:\Program files\broadcom\broadcom 802.11 Network adapter\driver; C:\Program Files (x86) \nvidia Corporation\physx\common; C:\PROGRAM FILES (X86) \intel\icls client\; C:\PROGRAM Files\intel\icls client\; C:\Windows\SYSTEM32; C:\Windows; C:\Windows\SYSTEM32\WBEM; C:\Windows\SYSTEM32\WINDOWSPOWERSHELL\V1.0\; C:\PROGRAM FILES (X86) \intel\opencl sdk\2.0\bin\x86; C:\PROGRAM FILES (X86) \intel\opencl sdk\2.0\bin\x64; C:\PROGRAM Files\intel\intel (R) MANAGEMENT ENGINE components\dal; C:\PROGRAM Files\intel\intel (R) MANAGEMENT ENGINE components\ipt; C:\PROGRAM FILES (X86) \intel\intel (R) MANAGEMENT ENGINE components\dal; C:\PROGRAM FILES (X86) \intel\intel (R) MANAGEMENT ENGINE Components\ipt; C:\PROGRAM FILES (X86) \lenovo\access connections\; C:\Program Files\widcomm\bluetooth software\; C:\Program Files\widcomm\bluetooth software\syswow64; C:\Program Files (x86) \intel\opencl sdk\3.0\bin\x86; C:\Program Files (x86) \intel\opencl sdk\3.0\bin\x64; E:\Ruby200\bin; E:\Program Files\tortoisesvn\bin; E:\Program files\mysql\mysql Utilities 1.3.4\; C:\Program Files\microsoft\web Platform installer\; C:\Program Files (x86) \microsoft Asp.net\asp.net Web Pages\v1.0\; C:\Program Files (x86) \ Windows Kits\8.0\windows performance toolkit\; C:\Program Files\Microsoft SQL Server\110\tools\binn\; E:\Program Files\java\jdk1.7.0_40\bin; C:\Program Files (x86) \microsoft SQL server\100\tools\binn\; C:\Program Files\Microsoft SQL Server\100\tools\binn\; C:\Program Files\Microsoft SQL Server\100\dts\binn\; F:\instantclient;.;;.;;. March 24, 2014 5:56:12 pm org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [setpropertiesrule]{server/service/ Engine/host/context} Setting ' source ' to ' org. Eclipse.jst.jee.server:FilterTest ' did not ' find a matching property. 24, 2014 5:56:13 pm Org.apache.coyote.AbstractPro Tocolhandler init info: Initializing protocolhandler ["http-bio-8080"] 24, 2014 5:56:13 pm Org.apache.coyote.AbstractProtocolHandler init info: Initializing protocolhandler ["ajp-bio-8009"] 24, 2014 5:56:13 pm Org.apache.catalina.startup.Catalina Load Info: Initialization processed in 1031 MS March 24, 2014 5:56:13 pm Org.apache.catalin A.core.standardservice startinternal Info: Starting service Catalina March 24, 2014 5:56:13 pm Org.apache.catalina.core.StandardEngine startinternal Info: Starting Servlet engine:apache tomcat/7.0.8 encodefilter Init  March 24, 2014 5:56:13 pm org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web application Directory Docs March 24, 2014 5:56:13 pm org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web application Directory Exam Ples March 24, 2014 5:56:13 pm org.apache.catalina.core.ApplicationContext Log Info: contextlistener:contextinitialized () March 24, 2014 5:56:13 pm org.apache.catalina.core.ApplicationContext Log Info: sessionlistener:contextinitialized () March 24, 2014 5:56:13 pm Org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web application Directory Host-manager March 24, 2014 5:56:13 pm org.apache.catalina.startup.HostConfig deploydirectory Info: Deploying Web Application Directory Manager March 24, 2014 5:56:14 pm org.apache.catalina.startup.HostConfig deploydirectory info: Deploying Web Application directory root March 24, 2014 5:56:14 pm Org.apache.coyote.AbstractProtocolHandler start Info: Starting Protocolhandler ["http-bio-8080"] 24, 2014 5:56:14 pm ORG.APACHE.COYOTE.ABstractprotocolhandler Start Info: Starting Protocolhandler ["ajp-bio-8009"] 24, 2014 5:56:14 pm Org.apache.catalina.startup.Catalina Start Information: Server Startup in 978 ms

Where there is the output of the Filter,init method, create a index.html file with the following content:

1 <! DOCTYPE html> 2 

Click the button on the index.html page,

At this point the console output content:

1 Encodefilter DoFilter

Each request will have such an output.

When you close Tomcat, be careful to observe the contents of the console output:

 March 24, 2014 6:08:33 pm org.apache.catalina.core.StandardServer await information: A valid shutdown command was received via the Shutdown port. Stopping the Server instance. 24, 2014 6:08:33 pm Org.apache.coyote.AbstractProtocolHandler Pause info: pausing Protocolha Ndler ["http-bio-8080"] 24, 2014 6:08:34 pm Org.apache.coyote.AbstractProtocolHandler Pause Info: pausing Protocolhandler ["ajp-bio-8009"] 24, 2014 6:08:35 pm org.apache.catalina.core.StandardService stopinternal Info: Stopping service Catalinaencodefilter Destroy March 24, 2014 6:08:36 pm org.apache.catalina.core.ApplicationContext Log Info: Sessionlistener:contextdestroyed () March 24, 2014 6:08:36 pm org.apache.catalina.core.ApplicationContext Log information: Contextlistener:contextdestroyed () March 24, 2014 6:08:37 pm org.apache.coyote.AbstractProtocolHandler Stop info: stopping Protocolhandler ["http-bio-8080"] 24, 2014 6:08:37 pm org.apache.coyote.AbstractProtocolHandler Stop info: stopping Protocolhandler ["ajp-bio-8009"] 

At this point the Fileter destroy method is called. The life cycle of the filter ends. This article contains some information, such as Server,service,container, and so on, maybe some people like me to start with a very little understanding of this, if you can find out how Tomcat and other Web containers work, if there is something I said unclear, or there are errors, Then please remind me, thank you.

Reference: Http://www.journaldev.com/1933/java-servlet-filter-example-tutorial

Java Servlet Filter

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.