Filter in JSP and application examples (reproduced)

Source: Internet
Author: User

Filter function. It enables the user to change a request and modify a response. Filter is not a servlet, it cannot produce a response, it can preprocess the request before a request arrives at the servlet, or it can handle response when it leaves the servlet. In other words, filter is actually a "Servlet Chaining" (servlet chain).

A filter includes: 1. Intercept before the servlet is invoked; 2. Check the servlet request before the servlet is invoked; 3. Modify the request header and request data as required; 4. Modify the response head and response data as required; 5. Intercepted after the servlet is invoked.

Popular point of view filter equivalent to the gas station, request is a road, response is a road, the destination is the servlet, where the gas station is located where the data operation can be controlled by you.

Some situations that require filters: (1) authentication filter (2) Log and Audit filter (3) Image conversion filter (4) Data compression filter (5) password filter (6) token filter (7) Filter (8) for triggering resource access Events XSLT filter (9) Media type chain filter

1. Batch set request encoding

In order to avoid the Chinese garbled problem of submitting data, it is troublesome to set request.setcharacterencoding ("gb2312") encoding format before each use of the request. Filter can block requests and responses to modify Servlets in bulk.

We write a encodingfilter.java to set the request encoding in bulk.

public class Encodingfilter implements Filter {

public void init (Filterconfig config) throws servletexception {}

public void Destroy () {}

public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain)         Throws IOException, servletexception {request.setcharacterencoding ("gb2312");     Chain.dofilter (request, response); }

}

The filter interface is implemented in this encodingfilter, and the three methods defined in the filter interface are implemented in Encodingfilter, where the Code of Dofilter () implements the main functions:

Set GB2312 encoding for the request and perform chain.dofilter () to continue with the following operation.

Convert to corresponding HttpServletRequest and HttpServletResponse to perform the following session operation and page redirection.

Similar to a servlet, it needs to be configured in Web. XML in order for the filter to work.

<filter> <filter-name>EncodingFilter</filter-name> <filter-class>sam. encodingfilter</filter-class> </filter> <filter-mapping> <filter-name>encodingfilter</ Filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

The filter label section defines the filters used, and the filter-mapping tag tells the server which requests to be processed by the filter. The/* Here indicates all requests,/represents the root path, * (asterisk) represents all requests, and together it becomes all requests under the root path.

In this way, all requests are intercepted by Encodingfilter and the specified gb2312 encoding is set on the request.

2. Using filter to control user access permissions for information security and other reasons, some pages in the project require users to meet certain conditions before they can access the user to enter the account number and password, if the information entered correctly in the session to do a successful mark,   The success sign here is that the username in the session has value; Thereafter, when requesting confidential information, it is possible to determine if there is a sign that the session has been successfully logged in, there is access, and no access is allowed.

Suppose the page we want to protect is admin/index.jsp

Write Securityfilter.java to control user access rights

public class Securityfilter implements Filter {public void DoFilter (ServletRequest request, Servletresponse Respo NSE, Filterchain chain) throws IOException, servletexception {httpservletrequest req = (httpservle     trequest) Request;     HttpServletResponse res = (httpservletresponse) response;     HttpSession session = Req.getsession ();     if (Session.getattribute ("username") = null) {Chain.dofilter (request, response); } else {Res.sendredirect ("..     /failure.jsp "); } }

Web. XML is configured as follows

<filter> <filter-name>SecurityFilter</filter-name> <filter-class>sam. securityfilter</filter-class> </filter> <filter-mapping> <filter-name>securityfilter</ Filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping>

Define the Securityfilter filter so that it filters all requests that match/admin/*, and all requests under the/admin/path will receive Securityfilter checks

Because filter is designed to be a variety of protocol services, the HTTP protocol is just one of them, Convert ServletRequest and Servletresponse to HttpServletRequest and HttpServletResponse for the following session operation and page redirection.

After getting the HTTP request, you can get the corresponding session of the request, determine whether the username variable in the session is NULL, if it is not NULL, the user is logged in, you can call Dofilter continue to request access to the resource. If NULL, the user is not logged in, prevents user access, and uses page redirection to jump to the failure.jsp page to display the prompt.

Because the location of the/failure.jsp is at the top level of the/admin/directory, two points can be added to the failure.jsp correctly, two points (.. ) represents the upper-level path of the current path.

3. Log and Audit filter

public class Loggingfilter implements Filter {private filterconfig filterconfig = null;

public void init (Filterconfig config) throws servletexception {this.filterconfig = config; }

Here is the output log to the server console, here is the demo, more is the use of log4j public void DoFilter (ServletRequest request, servletresponse response, Filterch    Ain chain) throws IOException, servletexception {String address = request.getremoteaddr ();    Filterconfig.getservletcontext (). log ("User IP:" + address);  Chain.dofilter (request, response); }

public void Destroy () {}}

Web. XML configuration <filter> <filter-name>LoggingFilter</filter-name> <filter-class>samjava.filter. loggingfilter</filter-class> </filter> <filter-mapping> <filter-name>loggingfilter</ Filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

4.filter the so-called feature request Mappings filter-mapping and servlet-mapping all map the corresponding filter or servlet to a url-pattern, and when a customer initiates a request, The server first matches this request to all the Url-pattern defined in Web. XML, and then executes the filter and servlet that matched the pass.

You can define url-pattern in three different ways.

directly maps a request.

<servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/TestServlet< /url-pattern> </servlet-mapping>

Maps all requests under a path.

<servlet-mapping> <servlet-name>EncodingFilter</servlet-name> <url-pattern>/*</ Url-pattern> </servlet-mapping>

It is important to note that this notation must be written in the form of an absolute path, even if the mapping of all requests is written AS/* and cannot be simplified into *.

A class of requests with the same end mapping.

<servlet-mapping> <servlet-name>ControllerServlet</servlet-name> <url-pattern>*.do</ Url-pattern> </servlet-mapping>

It is important to note that this request mapping cannot specify a path, it must end with an asterisk (*) and cannot be written in/*.do form.

5. Filter chain We use two filters, Encodingfilter is responsible for setting the code, Securityfilter is responsible for controlling permissions, then how do these two filters work?

All mysteries are in the filterchain of the filter. The server is assembled sequentially into a chain as defined by the filter in Web. XML, then executes the Dofilter () method one at a time. 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 execution order is:

(1) Execution of the previous part of Encodingfilter.dofilter () Chain.dofilter (): Request.setcharacterencoding ("gb2312");

(2) Perform the previous part of Chain.dofilter () in Securityfilter.dofilter (): Determine if the user is logged in

(3) If the user is logged in, access the requested resource:/admin/index.jsp

(4) If the user is not logged in, the page is redirected to:/failure.jsp

(5) The execution of Securityfilter.dofilter () after the Chain.dofilter () part;

(6) The execution of Encodingfilter.dofilter () after the Chain.dofilter () part;

The simple point is that filter will be called in the order in which it is declared in the Web. xml file.

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. Pay particular attention to the order of execution of the filter chain, like encodingfilter must be placed before all filters (in the Web. xml file) to ensure that the correct encoding is set before using the data in the request.

Detailed configuration of 6.filter we have already learned the basic use of filter, and there are some details that work in special cases.

In servlet-2.3, filter filters all requests, including the use of forward forwarding requests within the server and <%@ include file= "/index.jsp"%>.

In the servlet-2.4 filter is blocked by default only external submissions, forward and include these internal forwarding will not be filtered, but sometimes we need to forward to use the filter, which requires the following configuration.

<filter> <filter-name>TestFilter</filtername> <filter-class>sam. testfilter</filter-class> </filter> <filter-mapping> <filter-name>testfilter</ filtername> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <disp Atcher>forward</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>exception </dispatcher> </filter-mapping>

This testfilter will filter requests in all States. If we do not set it, the default is request. And exception is in the case of iserrorpage= "true", this is not much use, look at it.

Here forward is the solution request.getdispatcher ("index.jsp"). Forward (request, response); The key to filter cannot be triggered, The filter can be triggered when the configuration is forward later on.

Filter in JSP and application examples (reproduced)

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.