Filter and Filterchain use detailed classification: Java programming 2010-12-29 20:08 26691 people read reviews (20) Favorites Report Filterencodingservletnullwebstring
First, Filter Introduction and use of
What is a filter?
Similar to Servlets, filters are Web application components that can be bound to a Web application. But unlike other Web application components, filters are "chained" during container processing. This means that they will access an incoming request before the Servlet processor, and access the response information before the outgoing response is returned to the customer. This access allows the filter to examine and modify the contents of the request and response.
Where are the filters suitable for?
L Model A new feature of a Web application that can be added to a Web application or removed from a Web application without rewriting the base-level application code;
L Add new functionality to the previous code.
Where is the filter placed in the container structure?
Before a filter is placed on a web resource, it can intercept incoming requests before the request arrives at the Web resource it applies to, which can be a servlet, a JSP page, or even an HTML page, and intercept the output request before it returns to the customer. Filter: Used to intercept requests between the client and the requested resource for the purpose of reusing code. The filter chain, which is first configured in Web. XML and which is called first. Some initialization parameters can also be configured in the filter.
Filter in Java is not a standard servlet, it cannot handle user requests, nor can it generate responses to clients. It is mainly used for pretreatment of HttpServletRequest, but also for post-processing of HttpServletResponse, which is a typical processing chain.
Filter has several uses:
L INTERCEPT the client's httpservletrequest before HttpServletRequest arrives at the servlet.
L Check the HttpServletRequest as needed, and you can also modify the HttpServletRequest header and data.
L Intercept HttpServletResponse before HttpServletResponse arrives at the client.
L Check the HttpServletResponse as needed, you can modify the HttpServletResponse header and data.
There are several types of Filter:
User-Authorized Filter:filter is responsible for checking the user request and filtering the user's illegal request according to the request.
L Log Filter: Detailed logging of certain special user requests.
The filter that is responsible for decoding: Includes request decoding for non-standard encoding.
L can change the xsltfilter of XML content and so on.
A filter is responsible for intercepting multiple requests or responses: one request or response can also be intercepted by multiple requests.
Creating a filter takes only two steps: (1) Creating a filter processing class:
(2) Configure filter in the Web. xml file. The Create Filter must implement the Javax.servlet.Filter interface, which defines three methods in the interface. void init (filterconfig config): Used to complete the initialization of the filter. void Destroy (): To complete the collection of some resources before the filter is destroyed. void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain): Implements the filtering function, which is the additional processing added to each request and response.
Filter filters also have a life cycle: init ()->dofilter ()->destroy (), driven by the filter element in the deployment file. In servlet2.4, the filter can also be used to request the dispatcher, but must be declared in Web. XML, <dispatcher>include or forward or request or error</dispatcher> The element is in filter-mapping.
Filter Common scenarios:
Example one, log records, when a request arrives, in the filter to log records. After the processing is completed, enter the filter or process for subsequent processing.
Step 1: Write the Filter class
Package test.filter;
import Javax.servlet.Filter;
import Javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import Javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
Public class Logfilter implements Filter {
Private Filterconfig config;
Implementing the Initialization method
Public void init (filterconfig config) {
this. config = config;
}
Implementing the Destruction method
Public void Destroy () {
this. config = null;
}
Public void DoFilter (servletrequest request, servletresponse response,
Filterchain chain) {
Get the ServletContext object for logging
ServletContext context = this. Config.getservletcontext ();
long before = System. Currenttimemillis ();
System. out. println ("Start filtering ... ");
Convert requests to httpservletrequest requests
HttpServletRequest hrequest = (httpservletrequest) request;
Record log
Context.log ("Filter has intercepted the user's requested address:" + hrequest.getservletpath ());
Try {
The Filter is only chained, and the request is still forwarded to the destination address.
Chain.dofilter (request, response);
} catch (Exception e) {
E.printstacktrace ();
}
long after = System. Currenttimemillis ();
Record log
Context.log ("Filter End");
Record the log again
Context.log ("request is located to" + ((HttpServletRequest) requests). Getrequesturi ()
+ "The time Spent is:" + (After-before));
}
}
In the above request filter, only the requested URL is recorded in the log, the Chain.dofilter (request,reponse) method is executed for all requests, and when filter is filtered on the request, the request is still sent to the destination address.
Step 2: Configure the filter in Web. xml
<!--define Filter--
<filter>
<!--Filter name--
<filter-name>log</filter-name>
<!--Filter Implementation class--
<filter-class> test.filter.logfilter</filter-class>
</filter>
<!--define Filter intercept address--
<filter-mapping>
<!--Filter name--
<filter-name>log</filter-name>
<!--Filter is responsible for intercepting the URL--
<url-pattern>/filter/*</url-pattern>
</filter-mapping>
With the above steps, you can access the URI at this time. The specific access log is generated in the localhost file in the log file after the specific access. As shown below:
2010-12-28 21:12:50 Org.apache.catalina.core.ApplicationContext Log
Info: The time it took to locate the request to/examples/jsp/jsp2/el/basic-arithmetic.jsp was: 0
2010-12-28 21:14:55 Org.apache.catalina.core.ApplicationContext Log
Info: Filter has intercepted the user's request address:/jsp/jsp2/el/basic-comparisons.jsp
2010-12-28 21:14:56 Org.apache.catalina.core.ApplicationContext Log
Info: End of filter
Example two, the code correction, when there is a new request, you need to re-encode the characters sent by the user, so that it can meet the server encoding format.
1, Write Encodingfilter class
Package test.filter;
import java.io.IOException;
import Javax.servlet.Filter;
import Javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import Javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Public class Encodingfilter implements Filter {
Private Filterconfig filterconfig = null;
Private String encoding = null;
Implementing the Destruction method
Public void Destroy () {
encoding = NULL;
}
For specific filtering
Public void DoFilter (servletrequest request, servletresponse response,
Filterchain chain) throws IOException, servletexception {
Get the ServletContext object for logging
ServletContext context = this. Filterconfig.getservletcontext ();
Context.log ("Start setting encoding format");
String encoding = GetEncoding ();
if (encoding = = null) {
encoding = "gb2312";
}
Set the specified encoding on the request
request.setcharacterencoding (encoding);
Chain.dofilter (request, response);
Context.log ("Successfully set encoding format");
}
Initialize configuration
Public void init (filterconfig filterconfig) throws servletexception {
this. filterconfig = Filterconfig;
this. Encoding = Filterconfig.getinitparameter ("encoding");
}
Private String GetEncoding () {
return this. encoding;
}
}
Step 2: Configure the filter in Web. xml
<!--define Filter--
<filter>
<!--Filter name--
<filter-name>encoding</filter-name>
<!--Filter Implementation class--
<filter-class> test.filter.encodingfilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<!--define Filter intercept address--
<filter-mapping>
<!--Filter name--
<filter-name> encoding </filter-name>
<!--Filter is responsible for intercepting the URL--
<url-pattern>/encode/*</url-pattern>
</filter-mapping>
With the above steps, you can access the URI at this time.
Example three, the user authority authentication, when the user sends the request, may authenticate to the user's identity information, if can pass the verification then carries on the other operation, otherwise directly does not enter the next processing.
1, write the identity authentication Securityfilter class
Package test.filter;
import java.io.IOException;
import Javax.servlet.Filter;
import Javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import Javax.servlet.ServletContext;
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.HttpSession;
Public class Securityfilter implements Filter {
Private Filterconfig Filterconfig;
Initialization method implementation
@Override
Public void init (filterconfig filterconfig) throws servletexception {
this. filterconfig = Filterconfig;
}
Filtering for identity authentication
@Override
Public void DoFilter (servletrequest request, servletresponse response, Filterchain chain)
throws IOException, Servletexception {
ServletContext context = this. Filterconfig.getservletcontext ();
HttpServletRequest req = (httpservletrequest) request;
HttpServletResponse res = (httpservletresponse) response;
HttpSession session = Req.getsession ();
Log in Before you can proceed to the next step, or go directly to the error prompt page
if (Session.getattribute ("username")! = null) {
Context.log ("Identity authentication passed, go to next processing");
Chain.dofilter (request, response);
} Else {
Context.log ("Failure of identity authentication, direct return");
Res.sendredirect (".. /failure.jsp ");
}
}
Implementing the Destruction method
@Override
Public void Destroy () {
this. filterconfig = null;
}
}
Step 2: Configure the filter in Web. xml
<!--define Filter--
<filter>
<!--Filter name--
<filter-name>security</filter-name>
<!--Filter Implementation class--
<filter-class> test.filter.securityfilter</filter-class>
</filter>
<!--define Filter intercept address--
<filter-mapping>
<!--Filter name--
<filter-name> Security </filter-name>
<!--Filter is responsible for intercepting the URL--
<url-pattern>/security/*</url-pattern>
</filter-mapping>
With the above steps, you can access the URI at this time. At this point, if you can get the username value in the session, it will go directly to the next step, otherwise go directly to the error page.
second, the filter chain Filterchain
Two filters, Encodingfilter is responsible for setting the encoding, Securityfilter is responsible for controlling the permissions, the server will be in accordance with the Web. XML filter defined by the sequential assembly into a chain, and then execute one of the Dofilter () method. The order of execution as shown, executes the code before the first filter's Chain.dofilter (), the second filter's Chain.dofilter () before the code, the requested resource, the second filter's Chain.dofilter () after the code, The code after the first filter's Chain.dofilter (), and finally returns the response.
The code order executed is:
L perform the part before Chain.dofilter () in Encodingfilter.dofilter ();request.setcharacterencoding (encoding);
L perform the previous part of Chain.dofilter () in Securityfilter.dofilter (): Determine if the user is logged in.
L access the requested resource if the user is logged in.
L If the user is not logged in, the page is redirected to:/failure.jsp.
L EXECUTE the part after Chain.dofilter () in Securityfilter.dofilter (): There is no code here.
L EXECUTE the section after Chain.dofilter () in Encodingfilter.dofilter (): Writes the completed log.
The benefit of the filter chain is that it can be interrupted at any time during execution, as long as no chain.dofilter () is executed and no subsequent filters and requested content are executed. In practice, it is important to pay particular attention to the order of execution of the filter chain, as Encodingfilter must be placed before all filters to ensure that the correct encoding is set before using the data in the request.
Use of filter and Filterchain