Servlet authoring filter
Servlet filters can dynamically intercept requests and responses to transform or use the information contained in the request or response.
You can attach one or more Servlet filters to a Servlet or a set of Servlet.Servlet filters can also be attached to JavaServer Pages (JSP) files and HTML pages. Call all additional Servlet filters before calling Servlet.
Servlet filters are Java classes that can be used for Servlet programming todo the following:
Intercept client requests before accessing back-end resources.
The responses from the server are processed before they are sent back to theclient.
Various types of filters recommended according to the specification:
Authentication Filters.
Data compression Filters.
EEncryption Filters.
Triggers a resource access event filter.
Image Conversion Filters.
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters.
XSL/T filter (XSL/T Filters) to convert XML content.
The filter uses the Web deployment descriptor web.xml
and then map to the Servlet name or URL schema in your application’s deployment descriptor.
When the Web container starts the Web application, it creates an instance ofeach filter that you declare in the deployment descriptor.
The execution order of Filter is similar to that of the web.xml
the configuration order in the configuration file is the same, and Filter is generally configured before all Servlet.
Servlet filter method
The filter is an implementation of javax.servlet.Filter
the Java class of the interface. javax.servlet.Filter
the interface defines three methods:
Serial number |
Method & description |
---|---|
1 |
|
2 |
|
3 |
|
FilterConfig usage
Filter’s init
method provides a FilterConfig
object.
Such as the web.xml
file configuration is 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>Rookie Tutorial</param-value>
</init-param>
</filter>
In init
method use FilterConfig
object to get parameters:
public void init(FilterConfig config) throws ServletException {
// Get initialization parameters
String site = config.getInitParameter("Site");
// Output initialization parameters
System.out.println("Site Name: " + site);
}
Servlet filter instance
The following is an example of a Servlet filter that outputs the name and address of the Web site. This example gives you a basic understanding of Servlet filters, and you can write more complex filter applications using the same concepts:
package com.runoob.test;
//Import necessary Java libraries
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("Website URL:http://www.runoob.com");
// Send the request back to the filtering chain
chain.doFilter(request,response);
}
public void destroy( ){
/* Called before the Filter instance is removed from the service by the Web container */
}
}
Use the above mentioned here. DisplayHeader.java
as an example:
//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 method 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 - Rookie 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 a filter and then map to a URL or Servlet in much the same way as defining a Servlet and then mapping to an URL schema. In the deployment descriptor file web.xml
create the following entry for the filter tag in:
<?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>Rookie 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>
<!-- The package it is in -->
<servlet-class>com.runoob.test.DisplayHeader</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayHeader</servlet-name>
<!-- Visited website -->
<url-pattern>/TomcatTest/DisplayHeader</url-pattern>
</servlet-mapping>
</web-app>
The above filter applies to all Servlet because we specify in the configuration /\*
. If you only want to apply filters to a small number of Servlet, you can specify a specific Servlet path.
Now try calling any Servlet in the usual way, and you will see the logs generated in the Web server. You can also use the Log4J logger to log the above to a separate file.
Next, we visit the instance address http://localhost:8080/TomcatTest/DisplayHeader, and take a look at the output in the console, as shown below:
Use multiple filters
Web applications 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.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 order of filter
In web.xml filter-mapping
The order of elements determines the order inwhich the Web container applies the filter to the Servlet. To reverse the order of the filters, you only need to use the web.xml
invert in file filter-mapping
elements are fine.
For example, the above example will apply LogFilter first and 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 configuring each node description
<filter>
specify a filter.<filter-name>
used to specify a name for the filter, and the content of the element cannot be empty.<filter-class>
element is used to specify the fully qualified class nameof the filter.<init-param>
element is used to specify initialization parameters for the filter, and its child elements<param-name>
specify the name of theparameter<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>
element is used to set the resource 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<filter-name>
the child element is used to set the registered name of the filter. The value must be in the<filter>
the name of the filter declared in the element<url-pattern>
set the request path intercepted by filter (URL style associated with the filter)
<servlet-name>
specifies the name of the Servlet intercepted by the filter.<dispatcher>
specifies the way in which the resource intercepted by the filter is called by the Servlet container, which can be one ofREQUEST
,INCLUDE
,FORWARD
, andERROR
. The default isREQUEST
. Users can set multiple child elements to specify Filter intercepts multiple ways of calling resources.The
<dispatcher>
values that can be set by child elements and their meaningREQUEST
:When the user accesses the page directly, the Web container willcall the filter If the target resource is through theRequestDispatcher
ofinclude()
orforward()
, the filter will not be called when the method is accessed.INCLUDE
:If the target resource is through theRequestDispatcher
oftheinclude()
filter is called when the method is accessed. Otherwise,the filter will not be called.FORWARD
:If the target resource is through theRequestDispatcher
of``forward()`` when the method is accessed, the filter will be called; otherwise, the filter will not be called.ERROR
:If the target resource is called through a declarative exception handling mechanism, the filter will be called Otherwise, the filter will notbe called.