Chapter 9. Servlet Writing Filters

Keywords: Programming xml Java Web Server JSP

Articles Catalogue

About this article

Understanding some servlet concepts, this edition of the article only makes some changes to the format of the article, the pictures used in the article are from the Runoob website.

Thank

Thank you for the information provided by Runoob, official information address Servlet tutorial

Servlet Writing Filters

Servlet filters can dynamically intercept requests and responses to transform or use information contained in requests or responses.

One or more servlet filters can be attached to a servlet or a set of servlets. Servlet filters can also be attached to JavaServer Pages (JSP) files and HTML pages. Call all additional Servlet filters before calling the Servlet.

Servlet filters are Java classes that can be used for Servlet programming. They can achieve the following purposes:

  • Intercept client requests before they access back-end resources.
  • The server's responses are processed before they are sent back to the client.

Various types of filters recommended by the specification:

  • Authentication Filters.
  • Data compression Filters.
  • Encryption Filters.
  • Trigger the resource access event filter.
  • Image Conversion Filters.
  • Logging and Auditing Filters.
  • MIME-TYPE Chain Filters.
  • Tokenizing Filters.
  • XSL/T Filters (XSL/T Filters) transform XML content.

The filter is declared through the XML tag in the Web deployment descriptor (web.xml), and then mapped to the Servlet name or URL schema in the deployment descriptor of your application.

When the Web container starts a Web application, it creates an instance of each filter you declare in the deployment descriptor.

The order of Filter execution is the same as the order of configuration in the web.xml configuration file. In general, the Filter is configured before all Servlet s.

Servlet filter method

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

Serial number Method-description
1 The public void doFilter (Servlet Request, Servlet Response, FilterChain) method completes the actual filtering operation. When the client requests a URL matching the filter settings, the servlet container will call the filter's doFilter method first. FilterChain users access subsequent filters.
2 When the public void init (FilterConfig filter Config) web application starts, the web server will create an instance object of Filter, call its init method, read the web.xml configuration, and complete the initialization function of the object, so as to prepare for the interception of subsequent user requests (filter object will only be created once, init side) The law will only be enforced once. Developers can obtain FilterConfig objects representing the current filter configuration information through init method parameters.
3 The public void destroy() Servlet container calls this method before destroying the filter instance, in which the resources occupied by the Servlet filter are released.

FilterConfig uses

A FilterConfig object is provided in the init method of Filter.

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

<filter>
    <filter-name>LogFilter</filter-name>
    <filter-class>com.runoob.test.LogFilter</filter-class>
    <init-param>
        <param-name>Site</param-name>
        <param-value>Newbie Course</param-value>
    </init-param>
</filter>

In the init method, the filter Config object is used to obtain parameters:

public void  init(FilterConfig config) throws ServletException {
    // Get initialization parameters
    String site = config.getInitParameter("Site"); 
    // Output initialization parameters
    System.out.println("Website Name: " + site); 
}

Servlet filter instance

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

package com.runoob.test;

//Import the required java Libraries
import javax.servlet.*;
import java.util.*;

//Implementing the 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("Website Name: " + site); 
    }
    public void  doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException {

        // Output site name
        System.out.println("Website address: http://www.runoob.com");

        // Return the request back to the filter chain
        chain.doFilter(request,response);
    }
    public void destroy( ){
        /* Called before the Filter instance is removed from the service by the Web container */
    }
}

Here we use the DislayHeader. Java mentioned earlier as an example:

//Import the required 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")

//Extending the HttpServlet class
public class DisplayHeader extends HttpServlet {

    // Method of handling GET method requests
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Setting Response Content Type
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "HTTP Header Request instance - An example of a novice bird course";
        String docType =
            "<!DOCTYPE html> \n";
            out.println(docType +
            "<html>\n" +
            "<head><meta charset=\"utf-8\"><title>" + title + "</title></head>\n"+
            "<body bgcolor=\"#f0f0f0\">\n" +
            "<h1 align=\"center\">" + title + "</h1>\n" +
            "<table width=\"100%\" border=\"1\" align=\"center\">\n" +
            "<tr bgcolor=\"#949494\">\n" +
            "<th>Header Name</th><th>Header value</th>\n"+
            "</tr>\n");

        Enumeration headerNames = request.getHeaderNames();

        while(headerNames.hasMoreElements()) {
            String paramName = (String)headerNames.nextElement();
            out.print("<tr><td>" + paramName + "</td>\n");
            String paramValue = request.getHeader(paramName);
            out.println("<td> " + paramValue + "</td></tr>\n");
        }
        out.println("</table>\n</body></html>");
    }
    // Method of handling POST method requests
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Servlet Filter Mapping in Web.xml

Defining filters and then mapping them to a URL or Servlet is roughly the same as defining a Servlet and then mapping them to a URL schema. Create the following entry for the filter tag in the deployment descriptor file web.xml:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<filter>
  <filter-name>LogFilter</filter-name>
  <filter-class>com.runoob.test.LogFilter</filter-class>
  <init-param>
    <param-name>Site</param-name>
    <param-value>Newbie Course</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>LogFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>  
  <!-- Class name -->  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- Where is the bag -->  
  <servlet-class>com.runoob.test.DisplayHeader</servlet-class>  
</servlet>  
<servlet-mapping>  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- Accessed Web Sites -->  
  <url-pattern>/TomcatTest/DisplayHeader</url-pattern>  
</servlet-mapping>  
</web-app>  

The above filters apply to all servlets because we specify /* in the configuration. If you only want to apply filters on a few Servlets, you can specify a specific Servlet path.

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

Next, let's visit the instance address. http://localhost:8080/TomcatTest/DisplayHeader Then output from the console as follows:

Use multiple filters

Web applications 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, and the rest of the processing is roughly the same as described above.

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>com.runoob.test.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>com.runoob.test.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>

Application sequence of filters

The order of filter-mapping elements in web.xml determines the order in which Web containers apply filters to Servlet s. To reverse the order of filters, you only need to reverse the filter-mapping element in the web.xml file.

For example, the above example will apply LogFilter first, then AuthenFilter, but the following example will reverse 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>

Description of each node in web.xml configuration

  • Specify a filter.
    • <filter-name> is used to specify a name for the filter, and the content of the element cannot be empty.
    • The < filter-class > element is used to specify the fully qualified class name of the filter.
    • The < init-param > element is used to specify initialization parameters for the filter. Its child elements < param-name > specify the name of the parameter and < param-value > specify the value of the parameter.
    • In filters, you can use the FilterConfig interface object to access initialization parameters.
  • Elements are used to set up resources that a Filter is responsible for intercepting. A resource intercepted by a Filter can be specified in two ways: the Servlet name and the request path for resource access.
    • The < filter-name > subelement is used to set the registry name of the filter. The value must be the name of the filter declared in the < Filter > element
    • <url-pattern> Sets the request path intercepted by the filter (the URL style associated with the filter)
  • <servlet-name> Specifies the Servlet name that the filter intercepts.
  • <dispatcher> specifies how the resources intercepted by the Filter are invoked by the Servlet container, which can be one of REQUEST,INCLUDE,FORWARD and ERROR, default REQUEST. Users can set up multiple < dispatcher > sub-elements to specify how filters intercept multiple calls to resources.
  • Values that can be set by child elements and their significance
    • REQUEST: When the user accesses the page directly, the Web container will call the filter. If the target resource is accessed through the include() or forward() method of RequestDispatcher, the filter will not be invoked.
    • INCLUDE: If the target resource is accessed through the include() method of RequestDispatcher, the filter will be invoked. In addition, the filter will not be called.
    • FORWARD: If the target resource is accessed through the forward() method of RequestDispatcher, 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, the filter will be invoked. In addition, the filter will not be called.

Posted by flyersman on Thu, 25 Jul 2019 20:38:20 -0700