English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Filters in JSP and Servlet are both Java classes.
Filters can dynamically intercept requests and responses to transform or use information contained in the request or response.
Filters can be attached to one or more Servlets or a group of Servlets. Filters can also be attached to JavaServer Pages (JSP) files and HTML pages.
Filters are Java classes available for Servlet programming that can achieve the following purposes:
Intercept these requests before the client's request accesses the backend resource.
Process these responses before the server's response is sent back to the client.
Various types of filters recommended by 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 (MIME-TYPE Chain Filters).
Tokenizing Filters).
XSL/T Filter (XSL/T Filters), convert XML content.
Filters are declared through XML tags in the Web deployment descriptor (web.xml) and then mapped to the Servlet name or URL pattern in the application's deployment descriptor.
When the Web container starts the Web application, it will create an example for each filter declared in the deployment descriptor.
The execution order of the Filter is consistent with the configuration order in the web.xml configuration file, and it is generally recommended to configure the Filter before all Servlets.
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 | public void doFilter(ServletRequest, ServletResponse, FilterChain) This method completes the actual filtering operation. When the client's request matches the URL set by the filter, the Servlet container will first call the doFilter method of the filter. FilterChain is used to access subsequent filters. |
2 | public void init(FilterConfig filterConfig) When a web application starts, the web server creates an example object of Filter and calls its init method to read the web.xml configuration, complete the initialization function of the object, and prepare for intercepting subsequent user requests (the filter object is created only once, and the init method is executed only once). Developers can obtain the FilterConfig object representing the current filter configuration information through the parameters of the init method. |
3 | public void destroy()} The Servlet container calls this method before destroying the filter example, where resources occupied by the Servlet filter are released. |
The init method of the Filter provides a FilterConfig object.
As configured in the web.xml file as follows:
<filter> <filter-name>LogFilter</filter-name> <filter-class>com.w3codebox.test.LogFilter</filter-class> <init-param> <param-name>Site</param-name> <param-value>Basics Tutorial Website</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("Website Name: " + site); }
Below is an example of a Servlet filter, which will output the website name and address. This example gives you a basic understanding of Servlet filters, which you can use to write more complex filter application programs:
//Import the 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("Website Name: " + site); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Output the site name System.out.println("Site URL: http:")//www.oldtoolbag.com"); // Pass the request back to the filter chain chain.doFilter(request, response); } public void destroy({) /* Call before the Filter example is removed from the service by the Web container */ } }
The code of the DisplayHeader.java file is as follows:
//Import the 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 to handle 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 - Basic Tutorial Website 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 to handle POST method requests public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Define the filter and then map it to a URL or Servlet, which 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 in
<?xml version="1.0" encoding="UTF-8"?> <web-app> <filter> <filter-name>LogFilter</filter-name> <filter-class>com.w3codebox.test.LogFilter</filter-class> <init-param> <param-name>Site</param-name> <param-value>Basics Tutorial Website</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> <!-- in the package --> <servlet-class>com.w3codebox.test.DisplayHeader</servlet-class> </servlet> <servlet-mapping> <servlet-name>DisplayHeader</servlet-name> <!-- The URL visited --> <url-pattern>/TomcatTest/DisplayHeader</url-pattern> </servlet-mapping> </web-app>
The above filter is applicable to all Servlets because we specify in the configuration /* . If you only want to apply the filter to a few Servlets, you can specify a specific Servlet path.
Now try to call any Servlet in a common way, and you will see the logs generated in the Web server. You can also use Log4The J logger is used to record the above logs into a separate file.
Next, we access this example address http://localhost:8080/TomcatTest/DisplayHeader, and then check the output content on the console
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 above, and the rest of the processing is roughly the same as explained above:
<filter> <filter-name>LogFilter</filter-name> <filter-class>com.w3codebox.test.LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Parameter</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>com.w3codebox.test.AuthenFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Parameter</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 in web.xml-The order of the '<mapping>' elements 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 order of the 'filter' in the web.xml file-The '<mapping>' element is sufficient.
For example, the above example will first apply LogFilter, and then apply 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>
<filter> specifies a filter.
<filter-The 'name' attribute is used to specify a name for the filter, the content of this element cannot be empty.
<filter-The '<class>' element is used to specify the complete qualified name of the filter.
<init-The '<param>' element is used to specify initialization parameters for the filter, its child element '<param'-The 'name' attribute specifies the name of the parameter, within '<param>-The 'value' attribute specifies the value of the parameter.
In the filter, the FilterConfig interface object can be used to access initialization parameters.
<filter-The '<mapping>' element is used to set the resources responsible for an intercepting Filter. A resource intercepted by a Filter can be specified in two ways: Servlet name and the request path of resource access
<filter-The 'name' attribute is used to set the registration name of the filter. This value must be the name of a filter declared in the '<filter>' element.
<url-pattern>sets the request path intercepted by the filter (the URL pattern associated with the filter)
<servlet-name>specifies the name of the Servlet intercepted by the filter.
The <dispatcher> specifies the way the Servlet container invokes the resources intercepted by the filter, which can be one of REQUEST, INCLUDE, FORWARD, and ERROR, with the default being REQUEST. Users can set multiple <dispatcher> sub-elements to specify the multiple calling methods for the Filter to intercept resources.
The values that can be set for the <dispatcher> sub-element and their meanings
REQUEST: The web container will call the filter when the user directly accesses the page. If the target resource is accessed through the RequestDispatcher's include() or forward() method, the filter will not be called.
INCLUDE: The filter will be called if the target resource is accessed through the RequestDispatcher's include() method. Other than that, the filter will not be called.
FORWARD: The filter will be called if the target resource is accessed through the RequestDispatcher's forward() method. Other than that, the filter will not be called.
ERROR: The filter will be called if the target resource is invoked through the declarative exception handling mechanism. Other than that, the filter will not be called.