Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JSP Filters

JSP Filters

Filters in both JSP and Servlet are Java classes.

Filters can dynamically intercept requests and responses to transform or make use of the information contained in them.

One or more filters can be attached to a single Servlet or a group of Servlets. Filters can also be attached to JavaServer Pages (JSP) files and HTML pages.

Filters are Java classes used in Servlet programming that can serve the following purposes:

Various types of filters suggested by the specification:

Filters are declared through XML tags in the Web deployment descriptor (web.xml), and then mapped to a Servlet name or URL pattern in your application's deployment descriptor.

When the Web container starts the Web application, it creates an instance for each filter you declared in the deployment descriptor.

The execution order of a Filter matches the order in which it is configured in the web.xml configuration file; typically a Filter is configured before all Servlets.

Servlet Filter Methods

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

No. Method & Description
1 public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method performs the actual filtering operation. When a client's request matches the URL set for the filter, the Servlet container calls the filter's doFilter method first. FilterChain is used to access subsequent filters.
2 public void init(FilterConfig filterConfig)
When the web application starts, the web server creates an instance of the Filter and calls its init method, reading the web.xml configuration and completing the object's initialization, thereby preparing to intercept subsequent user requests (the filter object is created only once, and the init method is executed only once). Through the parameters of the init method, developers can obtain a FilterConfig object representing the current filter configuration information.
3 public void destroy()
The Servlet container calls this method before destroying the filter instance, releasing the resources occupied by the Servlet filter in this method.

Using FilterConfig

A FilterConfig object is provided in the Filter's init method.

For example, the web.xml file is configured as follows:





    LogFilter

    com.runoob.test.LogFilter

    

        Site

        Runoob Tutorial

    

    

Use the FilterConfig object in the init method to obtain parameters:



public void  init(FilterConfig config) throws ServletException {

    // Get initialization parameters

    String site = config.getInitParameter("Site"); 

    // Output initialization parameters

    System.out.println("网站名称: " + site); 

}

JSP Filter Example

The following is an example of a Servlet filter that outputs the website name and address. This example gives you a basic understanding of Servlet filters; you can use the same concepts to write more complex filter applications:



//import necessary java libraries

import javax.servlet.*;

import java.util.*;



//Implement Filter class

public class LogFilter implements Filter  {

    public void  init(FilterConfig config) throws ServletException {

        // Get initialization parameters

        String site = config.getInitParameter("Site"); 



        // Output initialization parameters

        System.out.println("网站名称: " + site); 

    }

    public void  doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException {



        // Output site name

        System.out.println("站点网址:http://www.runoob.com");



        // Pass the request back to the filter chain

        chain.doFilter(request,response);

    }

    public void destroy( ){

        /* Call before the Filter instance is removed from the service by the Web container */

    }

}

The code of the DisplayHeader.java file is as follows:



//import necessary java libraries

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;



import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



@WebServlet("/DisplayHeader")



//Extend HttpServlet class

public class DisplayHeader extends HttpServlet {



    // Method for handling GET requests

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

    {

        // Set response content type

        response.setContentType("text/html;charset=UTF-8");



        PrintWriter out = response.getWriter();

        String title = "HTTP Header Request Example - Runoob Tutorial Example";

        String docType =

            " \n";

            out.println(docType +

            "\n" +

            "" + title + "\n"+

            "\n" +

            "

" + title + "

\n" +             "\n" +             "\n" +             "\n"+             "\n");         Enumeration headerNames = request.getHeaderNames();         while(headerNames.hasMoreElements()) {             String paramName = (String)headerNames.nextElement();             out.print("\n");             String paramValue = request.getHeader(paramName);             out.println("\n");         }         out.println("
Header 名称Header 值
" + paramName + " " + paramValue + "
\n");     }     // Method to handle POST requests     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         doGet(request, response);     } }

Servlet Filter Mapping in Web.xml

Defining a filter and then mapping it to a URL or Servlet is roughly the same as defining a Servlet and then mapping it to a URL pattern. In the deployment descriptor file web.xml create the following entry for the filter tag:



  

  



  LogFilter

  com.runoob.test.LogFilter

  

    Site

    Runoob Tutorial

  





  LogFilter

  /*



  

    

  DisplayHeader  

    

  com.runoob.test.DisplayHeader  

  

  

  DisplayHeader  

    

  /TomcatTest/DisplayHeader  

  

  

The above filter applies to all Servlets because we specified in the configuration /* . If you only want to apply the filter to a few Servlets, you can specify a particular Servlet path.

Now try invoking any Servlet in the usual way, and you will see the log generated in the Web server. You can also use the Log4J logger to record the above log to a separate file.

Next we access this example address http://localhost:8080/TomcatTest/DisplayHeader, and then look at the output in the console, as follows:

Using Multiple Filters

A Web application can define several different filters for specific purposes. Suppose you define two filters AuthenFilter and LogFilter. You need to create a different mapping as described below; the rest of the processing is roughly the same as explained above:





   LogFilter

   com.runoob.test.LogFilter

   

      test-param

      Initialization Paramter

   







   AuthenFilter

   com.runoob.test.AuthenFilter

   

      test-param

      Initialization Paramter

   







   LogFilter

   /*







   AuthenFilter

   /*



Filter Application Order

The order of the filter-mapping elements in web.xml determines the order in which the Web container applies filters to the Servlets. To reverse the order of the filters, you only need to reverse the filter-mapping elements in the web.xml file.

For example, the example above applies LogFilter first and then AuthenFilter, but the example below reverses this order:





   AuthenFilter

   /*







   LogFilter

   /*




Description of Each Node in the web.xml Configuration

- ` `Used to specify a name for the filter; the content of this element cannot be empty. - ` `The element is used to specify the fully qualified class name of the filter. - ` `The element is used to specify initialization parameters for the filter; its child element` `specifies the name of the parameter,` `specifies the value of the parameter. - In the filter, you can use the `FilterConfig` interface object to access the initialization parameters.
  • The element is used to set the resources that a Filter is responsible for intercepting. The resources a Filter intercepts can be specified in two ways: Servlet name and the request path for resource access.
    • The child element is used to set the registration name of the filter. This value must be the name of a filter declared in theelement.
    • Sets the request path intercepted by the filter (the URL pattern associated with the filter)
    - ` `The child element is used to set the registration name of the filter. This value must be in the` `name of a filter declared in the element - ` `Sets the request path intercepted by the filter (the URL pattern associated with the filter)
    • Specifies the name of the Servlet intercepted by the filter.
    • Specifies the way in which the resources intercepted by the filter are invoked by the Servlet container; it can beREQUEST,INCLUDE,FORWARDandERRORone of, the default isREQUEST. Users can set multiplechild elements to specify the various ways the Filter intercepts resources.
    • Values that the child element can be set to and their meanings
      • REQUEST: When a user accesses the page directly, the Web container will invoke the filter. If the target resource is accessed via the RequestDispatcher's include() or forward() method, then the filter will not be invoked.
      • INCLUDE: If the target resource is accessed via the RequestDispatcher's include() method, then the filter will be invoked. Otherwise, the filter will not be invoked.
      • FORWARD: If the target resource is accessed via the RequestDispatcher's forward() method, then the filter will be invoked; otherwise, the filter will not be invoked.
      • ERROR: If the target resource is invoked through a declarative exception-handling mechanism, then the filter will be invoked. Otherwise, the filter will not be invoked.
      - `REQUEST`: When a user accesses the page directly, the Web container will invoke the filter. If the target resource is accessed via the RequestDispatcher's include() or forward() method, then the filter will not be invoked. - `INCLUDE`: If the target resource is accessed via the RequestDispatcher's include() method, then the filter will be invoked. Otherwise, the filter will not be invoked. - `FORWARD`: If the target resource is accessed via the RequestDispatcher's forward() method, then the filter will be invoked; otherwise, the filter will not be invoked. - `ERROR`: If the target resource is invoked through a declarative exception-handling mechanism, then the filter will be invoked. Otherwise, the filter will not be invoked.