Java Servlet (quad) filter

Source: Internet
Author: User
Tags exception handling types of filters xsl
First, introduce

A Servlet filter can dynamically intercept requests and responses to transform or use information contained in a 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 the servlet.
A servlet filter is a Java class that can be used in servlet programming to achieve the following purposes:
(1) intercept these requests before the client requests access to the backend resources.
(2) process these responses before the server's response is sent back to the client.
Various types of filters are recommended according to the specification:
(1) Authentication filter (authentication Filters).
(2) Data compression filter (compression Filters).
(3) encryption filter (encryption Filters).
(4) triggers the resource access event filter.
(5) Image conversion filter (images conversion Filters).
(6) Logging and auditing filters (Logging and auditing Filters).
(7) Mime-type chain filter (Mime-type Chain Filters).
(8) Tagged filter (tokenizing Filters).
(9) xsl/t filter (xsl/t Filters), convert XML content

Filters are declared by XML tags in the WEB deployment descriptor (Web.xml), and then mapped to the Servlet name or URL pattern in the deployment descriptor of your application.

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

The order of execution of the filter is consistent with the configuration order in the Web.xml configuration file, which generally configures the filter before all the servlet. Second, the 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 public void Dofilter (ServletRequest, Servletresponse, Filterchain)
This method completes the actual filtering operation, and when the client requests the method to set a matching URL with the filter, the servlet container first invokes the Dofilter method of the filter. Filterchain user accesses subsequent filters.
2 public void init (Filterconfig filterconfig)
When the Web application starts, the Web server creates an instance object of the filter and invokes its Init method. Reads the Web.xml configuration, completes the initialization of the object, and prepares the interception for subsequent user requests (the filter object will only be created once and the Init method will only execute once). The developer uses the parameters of the Init method to obtain the Filterconfig object that represents the current filter configuration information.
3 public void Destroy ()
The servlet container calls this method before destroying the filter instance, releasing the resource occupied by the servlet filter in the method.
1 Filterconfig Use

A Filterconfig object is provided in the Init method of the Filter.
If the Web.xml file is configured as follows:

<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class> com.test.servlet.logfilter</filter-class>
    <init-param>
        <param-name>site</ Param-name>
        <param-value>servlet Filter Test </param-value>
    </init-param>
</filter >

To get parameters using the Filterconfig object in the Init method:

public void  init (filterconfig config) throws servletexception {
    //Get initialization parameter
    String site = Config.getinitparameter ("Site"); 
    Output initialization parameter
    System.out.println ("website name:" + site); 
}
Three, Servlet filter instance
package com.test.servlet;//import required Java library import javax.servlet.Filter; import
Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;

Import Javax.servlet.ServletResponse; Implements filter class public class Logfilter implements filter {public void init (Filterconfig config) throws Servletexcepti 

        On {//Get initialization parameter 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.IOExceptio

        N, servletexception {System.out.println ("Test interceptor output");
    Transmit the request back to the filter chain chain.dofilter (request,response); The public void Destroy () {/* calls the/}} 
before the Filter instance is removed from the service by the Web container
Package com.test.servlet;
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;
    Extended HttpServlet class @WebServlet ("/displayheader") public class Displayheader extends HttpServlet {//Processing Get method requests
        public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {

        Sets the response content type Response.setcontenttype ("Text/html;charset=utf-8");
        PrintWriter out = Response.getwriter ();
        String title = "HTTP Header request Instance"; String DocType = "<!
            DOCTYPE html> \ n ";  Out.println (DocType + " 

The

servlet filter Mappings in Web.xml (servlet filter Mapping)
defines the filter and then maps to a URL or servlet, which is roughly the same as defining a servlet and then mapping to a URL pattern. Create the following entry for the filter label in the deployment descriptor file Web.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "3.0" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee htt P://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "> <display-name></display-name> < welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter > <filter-name>LogFilter</filter-name> <filter-class>com.test.servlet.logfilter</ Filter-class> <init-param> <param-name>Site</param-name> <param-value>servlet Filter Test ;/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--> <servlet-class>com.test.servlet.DisplayHeader</servlet-class> </servlet> &LT;SERVL Et-mapping> <servlet-name>DisplayHeader</servlet-name> <!--web site--> <url-pattern>
 /webproject/displayheader</url-pattern> </servlet-mapping> </web-app>

The above filters apply to all Servlet because we specify/* in the configuration. If you only want to apply filters on a handful of servlet, you can specify a specific servlet path.
Now try calling any Servlet in a common way, and you will see the logs generated in the WEB server. You can also use the log4j logger to record the above log in a separate file.
Next we visit the instance address Http://localhost:8080/WebProject/DisplayHeader, and then look at the output in the console as follows:
Iv. Use of 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 remainder is roughly the same as explained above:

<filter> <filter-name>LogFilter</filter-name> <filter-class> Com.test.servlet.logfilter</filter-class> <init-param> <PARAM-NAME>TEST-PARAM</PARAM-NAME&G
      T <param-value>initialization paramter</param-value> </init-param> </filter> <filter> & Lt;filter-name>authenfilter</filter-name> <filter-class>com.test.servlet.authenfilter</ filter-class> <init-param> <param-name>test-param</param-name> <param-value>init Ialization paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name& Gt Logfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <
Filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 
v. Application Order of Filters

The order of the filter-mapping elements in the web.xml determines the order in which the Web container applies filters to the Servlet. 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 instance will first apply the Logfilter and then apply Authenfilter, but the following example reverses 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>
Six, Web.xml Configuration each node description

<filter>Specifies a filter.
<filter-name>Used to specify a name for the filter, and the contents of the element cannot be empty.
<filter-class>element is used to specify the full qualified class name of the filter.
<init-param>element is used to specify the initialization parameter for the filter, its child element <param-name> the name of the specified parameter,<param-value> the value of the specified parameter.
In a filter, you can use the Filterconfig interface object to access initialization parameters.
<filter-mapping>element is used to set the resources that a Filter is responsible for intercepting. A filter-blocking resource 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 registration name of the filter. The value must be the name of the filter declared in the <filter> element
<url-pattern>Sets the request path that the filter intercepts (filter associated URL style)
<servlet-name>Specifies the servlet name that the filter intercepts.
<dispatcher>Specifies how the resource intercepted by the filter is invoked by the Servlet container, which can be one of the Request,include,forward and the error, and the default request. Users can set multiple <dispatcher> child elements to specify how the Filter will intercept multiple calls to the resource.
<dispatcher>Values that child elements can set and their meaning
REQUEST: When a user accesses a page directly, the Web container invokes the filter. If the target resource is accessed through the requestdispatcher include () or forward () method, then the filter is not invoked.
INCLUDE: If the target resource is accessed through the RequestDispatcher include () method, the filter is invoked. In addition, the filter is not invoked.
FORWARD: If the target resource is accessed through the RequestDispatcher forward () method, the filter will be invoked, and the filter will not be invoked.
ERROR: If the target resource is invoked through a declarative exception handling mechanism, the filter is invoked. In addition, filters are not invoked

article from rookie tutorial : Servlet Write Filter | Rookie Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.