WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JSP writing filter


The filters in both JSP and Servlet are Java classes.

Filters can dynamically intercept requests and responses totransform or use the information contained in the request or response.

You can attach one or more filters to a servlet or a set of servlets. Filters can also be attached to JavaServer Pages (JSP) files and HTML pages.

The

filter is a Java class that can be used for servlet programming and can do the following:

  • Intercept these requests before the client's request accesses the backend resources.
  • Process these responses before the server's response is sent back to the client.

Various types of filters suggested according to the specification:

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

filter is declared through an XML tag in the web deployment descriptor (web.xml) and then mapped to the servlet name or URL pattern in your application's deployment descriptor.

When the web container launches the web application, it creates an instance for each filter you declare in the deployment descriptor.

Filter is executed in the same order as it is in the web.xml configuration file. Filters are generally configured before all servlets.

Servlet Filter method

Filter is an implementation javax.servlet.Filter Java class for the interface. javax.servlet.Filter The interface defines three methods:

Serial numbermethod & description
1public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method completes the actual filtering operation. When the client requests a URL that matches the filter settings, the servlet container will first call the filter's doFilter method. FilterChain is used to access subsequent filters.
2 public void init (FilterConfig filterConfig)
When the web application starts, the web server will create an instance of Filter and call its init Method, read the web.xml configuration, and complete the initialization of the object to prepare for interception of subsequent user requests (the filter object will only be created once and the init method will only be executed once). The developer can obtain the FilterConfig object representing the current filter configuration information through the parameters of the init method.
3 public void destroy ()
Servlet container calls this method before destroying the filter instance, in this method releases the servlet filter occupation H.

FilterConfig use

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

If the web.xml file is configured as follows:

<filter>
    <filter-name>LogFilter</filter-name>
    <filter-class>com.welookups.test.LogFilter</filter-class>
    <init-param>
        <param-name>Site</param-name>
        <param-value> Tutorial</param-value>
    </init-param>
    </filter>

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

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

JSP 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 write more complex filter applications using the same concepts:

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

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

        // Output site name
        System.out.println("Site URL:http://www.welookups.com");

        // Pass 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 */span>
    }
}

DisplayHeader.java The file code is as follows:

//Import the required java library
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 {

    // deal with GET Method request method
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Set the response content type
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "HTTP HeaderRequest Instance -  Tutorial Example ";
        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 for handling POST method requests 
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Servlet Filter Mapping in Web.xml

Define filters and then map to a URL or servlet, which is much the same as defining a servlet and then mapping to a URL pattern. 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.welookups.test.LogFilter</filter-class>
  <init-param>
    <param-name>Site</param-name>
    <param-value> tutorial</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 the bag is-->  
  <servlet-class>com.welookups.test.DisplayHeader</servlet-class>  
</servlet>  
<servlet-mapping>  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- Visited URL-->  
  <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 small number of servlets, you can specify a specific servlet path.

Trying to call any servlet in the usual way, you will see the logs generated in the web server. You can also use the Log4J logger to log the above logs into a separate file.

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

Use multiple filters

A web application can define several different filters for a specific purpose. 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 explained above:

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

Filter application order

The order of the filter-mapping elements in web.xml determines the order in which the web container applies filters to servlets. To reverse the order of the 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>

web.xml configuration node description

  • <filter>Specify a filter.
    • <filter-name>Used to assign a name to the filter whose content cannot be empty.
    • <filter-class>The element is used to specify the full qualified class name of the filter.
    • <init-param>The element is used to specify the initialization parameter for the filter, its child element <param-name>Specify the name of the parameter,<param-value> specifies the value of the parameter.
    • In the filter, you can use the FilterConfig interface object to access the initialization parameters.
  • <filter-mapping>The element is used to set a resource that the Filter is responsible for intercepting. A Filter intercepted resource can be specified in two ways: Servlet name and request path for resource access
    • <filter-name>The child element is used to set the registered name of the filter. The value must be in<filter>The name of the filter declared in the element
    • <url-pattern>Set the request path intercepted by filter (filter-associated URL style)
  • <servlet-name> Specify the name of the servlet that the filter intercepts.
  • <dispatcher>Specifies how the resource intercepted by the filter is called by the servlet container, which can be REQUEST,INCLUDE,FORWARDAnd one of ERROR, default REQUEST. Users can set multiple<dispatcher>The child element is used to specify that the Filter intercepts multiple invocations of the resource.
  • <dispatcher>The value that a child element can set and its meaning
    • REQUEST: When the user directly accesses the page, the web container will call the filter. If the target resource is accessed via the include() or forward() method of the RequestDispatcher, then the filter will not be called.
    • INCLUDE: This filter will be called if the target resource is accessed via the RequestDispatcher's include() method. Other than that, the filter will not be called.
    • FORWARD: If the target resource is accessed via the RequestDispatcher's forward() method, then the filter will be called, and the filter will not be called.
    • ERROR: This filter will be called if the target resource is called via a declarative exception handling mechanism. Other than that, the filter will not be called.