Filter for JSP

Source: Internet
Author: User

The following is referenced from http://wiki.jikexueyuan.com/project/jsp/writing-filters.html:

Both Servlets and JSP filters are Java classes that can be used in servlet and JSP programming for the following purposes:

    • Intercepts requests from the client before requesting access to the backend resources.

    • The response from the server operation before the response is sent back to the client.

There are various filters that conform to specifications:

    • Authentication filters.

    • Data compression Filters

    • Encryption filter.

    • The filter that triggers the resource access event.

    • Image conversion filter.

    • Logging and audit filters.

    • MIME type chain filter.

    • Tokenizing filter.

    • A xsl/t filter that transforms XML content.

Filters are deployed in the deployment descriptor file, Web. XML, and then mapped to the servlet or JSP name or URL pattern in the application's deployment descriptor. The deployment descriptor file Web. XML can be found in the <tomcat-installation-directory>\conf directory.

When the JSP container launches the Web application, it creates an instance for each filter declared in the deployment descriptor. Filters are executed in the order in which they are declared in the deployment descriptor.

First, the servlet filter method

A filter is a simple Java class that implements the Javax.servlet.Filter interface. The Javax.servlet.Filter interface defines three methods:

Method Description

public void DoFilter (ServletRequest, Servletresponse, Filterchain)

Because the client requests a response at the end of the chain, the container calls this method each time the request/response pair passes through the chain.

public void init (Filterconfig filterconfig)

This method is called by the Web container to indicate to the filter that it will be placed in the service.

public void Destroy ()

This method is called by the Web container to indicate to the filter that it will be removed from the service.

Second, JSP filter example

The following is an example of a JSP filter that outputs the client IP address and the current datetime every time a JSP file is accessed. This example will have a basic understanding of JSP filters, but you can use the same concepts to write more complex filter applications:

//Import required Java librariesImportJava.io.*;Importjavax.servlet.*;Importjavax.servlet.http.*;ImportJava.util.*;//Implements Filter class Public classLogfilterImplementsFilter { Public voidinit (filterconfig config)throwsservletexception{//Get init parameterString Testparam = Config.getinitparameter ("Test-param"); //Print the init parameterSystem.out.println ("Test Param:" +Testparam); }    Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsjava.io.IOException, servletexception {//Get The IP address of client machine. String ipAddress =request.getremoteaddr (); //Log the IP address and current timestamp.System.out.println ("IP" + ipAddress + ", time" +NewDate (). toString ()); //Pass request back down the filter chainChain.dofilter (Request,response); }    Public voiddestroy () {/*called before the Filter instance is removed from service by the Web container*/   }}

Compile the Logfilter.java in the usual way and put the Logfilter.class class file in <tomcat-installation-directory>/webapps/root/web-inf/ Classes (POM and eclipse can ignore this step).

Third, JSP filter mappings in Web. xml

Define the filter first, and then map the filter to the URL or the name of the JSP file, which is almost the same way as the URL pattern that defines the servlet and then maps to the Web. xml file. Create the following entry for the filter label in the deployment descriptor file Web. xml

<Filter>   <Filter-name>Logfilter</Filter-name>   <Filter-class>Logfilter</Filter-class>   <Init-param>      <Param-name>Test-param</Param-name>      <Param-value>Initialization paramter</Param-value>   </Init-param></Filter><filter-mapping>   <Filter-name>Logfilter</Filter-name>   <Url-pattern>/*</Url-pattern></filter-mapping>

The above filter will apply to all servlets and JSPs, because/* is specified in the configuration. If you want to apply a filter to a partial servlet or JSP, you can specify a specific servlet or JSP path.

Now try calling any servlet or JSP in a common way, and you will see the resulting login in the Web server log. You can use the log4j log to record the above logins in a separate file.

Iv. Use of multiple filters

A Web application may define different filters with a specific purpose. Consider this case, define two filters Authenfilter and Logfilter. The rest of the process will still be as explained above, in addition to creating a different mapping, as follows:

<Filter>   <Filter-name>Logfilter</Filter-name>   <Filter-class>Logfilter</Filter-class>   <Init-param>      <Param-name>Test-param</Param-name>      <Param-value>Initialization paramter</Param-value>   </Init-param></Filter><Filter>   <Filter-name>Authenfilter</Filter-name>   <Filter-class>Authenfilter</Filter-class>   <Init-param>      <Param-name>Test-param</Param-name>      <Param-value>Initialization paramter</Param-value>   </Init-param></Filter><filter-mapping>   <Filter-name>Logfilter</Filter-name>   <Url-pattern>/*</Url-pattern></filter-mapping><filter-mapping>   <Filter-name>Authenfilter</Filter-name>   <Url-pattern>/*</Url-pattern></filter-mapping>

Five, the application sequence of filters

The order of the filter-mapping elements in Web. XML determines the order in which the website container applies the filter to the servlet or JSP. To reverse the order of the filters, only the filter-mapping elements in the Web. xml file need to be reversed.

For example, the above example will first apply Logfilter and then apply authenfilter to any servlet or JSP, but the following example reverses this order:

<filter-mapping>   <Filter-name>Authenfilter</Filter-name>   <Url-pattern>/*</Url-pattern></filter-mapping><filter-mapping>   <Filter-name>Logfilter</Filter-name>   <Url-pattern>/*</Url-pattern></filter-mapping>

Test Project: Https://github.com/easonjim/5_java_example/tree/master/jspbasics/test8

Filter for JSP

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.