Java Web----Filters (filter)

Source: Internet
Author: User

1 What is the Filter?

Filter Javaweb One of three components, it is very similar to the servlet! No it filters are used to intercept requests, not to process requests.

When a user requests a servlet, the filter that is deployed on the request is executed first, and if Filter is "released", the servlet that executes the user's request is inherited, and if filter is not "released", the servlet requested by the user is not executed.

It can be understood that when a user requests a servlet, Tomcat executes the filter that is registered on the request, and then whether or not "release" is determined by the filter. Can be understood as filter to determine whether to invoke servlet! After executing the code for the servlet, the code after the filter is executed.


<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><filter><filter-name>hellofilter</filter-name ><filter-class>com.cug.filter.HelloFilter</filter-class></filter><filter-mapping> <filter-name>hellofilter</filter-name><url-pattern>/index.jsp</url-pattern></ Filter-mapping></web-app>

Package Com.cug.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;public class Hellofilter implements filter{@Overridepublic void Destroy () {}@ overridepublic void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {System.out.println ("Start dofilter~"); Chain.dofilter (request, response); System.out.println ("End dofilter~");} @Overridepublic void init (Filterconfig filterconfig) throws servletexception {}}

2 life cycle of filters

We have learned the life cycle of the servlet, so the life cycle of the filter is no more difficult!

    • Init (filterconfig): The filter instance is created when the server starts, and each type of filter creates only one instance, and is no longer created! After the filter instance is created, the init () method is called immediately to complete the initialization work, which is only executed once;
    • DoFilter (ServletRequest req,servletresponse res,filterchain chain): This method will be accessed every time the user accesses the target resource (<url->pattern> index.jsp</url-pattern>) ", if you need to" release ", then you need to call Filterchain's Dofilter (Servletrequest,servletresponse) method, If you do not call Filterchain's Dofilter () method, the target resource will not execute;
    • Destroy (): After the filter object is created, the server will always use the filter in the cache and will not normally destroy it. The filter object is typically destroyed when the server shuts down, and the server invokes the Destory () method of the filter object before destroying the filter object.

3 Filterconfig

The parameter type of the init () method in the filter interface is the Filterconfig type. It functions like servletconfig and corresponds to the configuration information in the Web. xml file. The following is a description of Filterconfig features:

    • ServletContext Getservletcontext (): Method of obtaining ServletContext;
    • String getfiltername (): Gets the configuration name of the filter and corresponds to the <filter-name> element;
    • String Getinitparameter (string name): Gets the initialization configuration of the filter, corresponding to the <init-param> element;
    • Enumeration Getinitparameternames (): Gets the name of all initialization parameters.


4 + Filter Execution order

A target resource can specify multiple filters, and the order in which the filters are executed is the order of deployment in the Web. xml file:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><filter><filter-name>myfilter1</filter-name ><filter-class>com.cug.filter01.MyFilter1</filter-class></filter><filter-mapping> <filter-name>myfilter1</filter-name><url-pattern>/index.jsp</url-pattern></ Filter-mapping><filter><filter-name>myfilter2</filter-name><filter-class> Com.cug.filter01.myfilter2</filter-class></filter><filter-mapping><filter-name> myfilter2</filter-name><url-pattern>/index.jsp</url-pattern></filter-mapping></ Web-app>

Package Com.cug.filter01;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;public class MyFilter1 implements filter{@Overridepublic void Destroy () {}@ overridepublic void DoFilter (ServletRequest arg0, Servletresponse arg1,filterchain arg2) throws IOException, servletexception {System.out.println ("Start myfilter1~"); Arg2.dofilter (arg0, arg1); System.out.println ("End MyFilter1");} @Overridepublic void init (Filterconfig arg0) throws servletexception {}}

package Com.cug.filter01;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;public class MyFilter2 implements filter{@Overridepublic void Destroy () {}@ overridepublic void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {System.out.println ("Start myfilter2~"); Chain.dofilter (request, response); System.out.println ("End myfilte2~");} @Overridepublic void init (Filterconfig filterconfig) throws servletexception {}} 
<%@ page language= "java" import= "java.util.*" pageencoding= "iso-8859-1"%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Because the MYFILTER1 is configured in front, the MyFilter1 Dofilter () method is executed first.

54 Ways to intercept

Let's do a test, write a filter, specify the filter resource as b.jsp, and then we directly access b.jsp in the browser, and you'll find the filter executed!

However, when we request.getrequestdispathcer ("/b.jsp"). Forward (Request,response) in a.jsp, the filter is no longer executed! That is, by default, only direct access to the target resource executes the filter, and forward executes the target resource without executing the filter!

public class Myfilter extends HTTPFilter {public void DoFilter (httpservletrequest request,httpservletresponse response, Filterchain chain) throws IOException, servletexception {System.out.println ("myfilter ..."); Chain.dofilter (Request, response);}}
<filter><filter-name>myfilter</filter-name><filter-class>cn.itcast.filter.MyFilter< /filter-class></filter><filter-mapping><filter-name>myfilter</filter-name>< Url-pattern>/b.jsp</url-pattern></filter-mapping>
  <body>   
  

Http://localhost:8080/filtertest/b.jsp--> Direct access to b.jsp, filter content is executed;

http://localhost:8080/filtertest/a.jsp--> access a.jsp, but a.jsp will forward to b.jsp, then the filter will not be executed!

In fact, the filter has four kinds of interception mode! They are: REQUEST, FORWARD, INCLUDE, ERROR.

    • REQUEST: Executes a filter when accessing the target resource directly. Include: direct access in the Address bar, form submission, hyperlinks, redirection, as long as the address bar can see the path of the target resources, is the request;
    • FORWARD: Forward access execution filter. including Requestdispatcher#forward () methods, <jsp:forward> tags are forwarded access;
    • Include: Contains access execution filters. including Requestdispatcher#include () methods, <jsp:include> tags are included access;
    • Error: When the target resource is configured as <error-page> in Web. XML, and there is an exception, the filter is executed when it is forwarded to the target resource.

You can add 0~n <dispatcher> sub-elements in <filter-mapping> to illustrate how the current access is blocked.

B.JSP is the target resource, the filter is executed when the b.jsp is requested directly

Filter is executed when forwarding to the b.jsp page

<filter-mapping><filter-name>myfilter</filter-name><url-pattern>/b.jsp</url-pattern ><dispatcher>request</dispatcher><dispatcher>forward</dispatcher></ Filter-mapping>

When no interception method is given, the default is request

<filter-mapping><filter-name>myfilter</filter-name><url-pattern>/b.jsp</url-pattern ></filter-mapping>
When forwarding to the B.jsp page, the filter is executed! Since <dispatcher>FORWARD</dispatcher> has been given, there is no default request! So filtering is only performed when forwarding to b.jsp
<filter-mapping><filter-name>myfilter</filter-name><url-pattern>/b.jsp</url-pattern ><dispatcher>FORWARD</dispatcher></filter-mapping>

In fact, the most commonly used is the request and forward two kinds of interception methods, and include and error are less useful! The include is better understood, we do not give the code here, students can be modified by forward way, to test their own. The error mode is not easy to understand, the following is an example of how to intercept the error:

When the user accesses the A.jsp page, an exception is thrown, which is 500!

The server will then forward to b.jsp, which will execute the filter before!
<filter-mapping><filter-name>myfilter</filter-name><url-pattern>/b.jsp</url-pattern ><dispatcher>error</dispatcher></filter-mapping><error-page><error-code>500 </error-code><location>/b.jsp</location></error-page>

  <body>  

6 Application Scenarios for filters

Application Scenarios for filters:

    • pre-processing is done before the target resource is executed, for example, by setting the encoding, which is usually released , only to do some preparation before the target resource is executed;
    • Pass conditions to determine whether the release, such as verifying whether the current user is logged in, or whether the user IP has been disabled;
    • After the target resources are executed, some follow-up special processing work is done, for example, the data of target resource is processed;

7 Setting the target resource

When you deploy filter in the Web. xml file, you can execute the target resource through "*":

<filter-mapping><filter-name>myfilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>
means to filter all resources

This feature is exactly the same as a servlet! With this feature, we can execute the filter when the user accesses the sensitive resource, for example: <url-pattern>/admin/*<url-pattern>, and can put resources that all administrators can access to the/admin path. The user's identity can then be verified by a filter.

You can also specify a target resource for <filter-mapping> as a servlet, for example:

<servlet><servlet-name>myservlet</servlet-name><servlet-class> Cn.itcast.servlet.myservlet</servlet-class></servlet><servlet-mapping><servlet-name> Myservlet</servlet-name><url-pattern>/abc</url-pattern></servlet-mapping><filter ><filter-name>myfilter</filter-name><filter-class>cn.itcast.filter.myfilter</ filter-class></filter><filter-mapping><filter-name>myfilter</filter-name>< Servlet-name>myservlet</servlet-name></filter-mapping>
&LT;URL-PATTERN&GT is not specified here, but instead specifies <servlet-name>! Note that it is the same as the configuration name of a servlet!
When a user accesses Http://localhost:8080/filtertest/abc, a servlet with the name Myservlet is executed, and a filter is executed.


Java Web----Filters (filter)

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.