Java Web Foundation Summary seven--filter and listener

Source: Internet
Author: User

Java Web Foundation Summary seven--filter and listenerA. Filter1. Filter Introduction

Filter is a very important technology in the servlet system. Filter means filters, so what does it filter? Is all Web resources managed by the Web server. such as JSP, Servlet, static picture file or static HTML file interception, so as to achieve some special functions. Its code logic performs some special operations before accessing these resources. Some advanced features, such as access control, encoding, and filtering of words, are implemented.

A filter interface is provided in the Servlet API, and we typically write a Java class to implement this interface. Enables users to intercept requests and responses to access before accessing a target resource.

2. How filter is implemented

Filter and Filterchain are a typical chain of responsibility design patterns. There is a Dofilter method in the filter interface, and when we write the filter and configure which Web resource to intercept, the Web server will call the filter's Dofilter method each time before accessing the Web resource, so Writing code within this method can be implemented by having a piece of code execute before invoking the target resource, letting the user access the Web resource, and then having a piece of code execute after invoking the target Web resource.

In a Web application, you can develop and write multiple filter combinations called a filterchain. The Web server decides which filter to call first, based on the order in which the filter is registered in the Web. xml file, and when the Dofilter method of the first filter is called, it creates a Filterchain object representing the filter chain that is passed to the method. In the Dofilter method, if the developer calls the Dofilter method of the Filterchain object, the Web server checks to see if there is a filter in the Filterchain object, and if so, the 2nd filter, if not, The target resource is called.

3. Filter development Steps

First, write the Java class to implement the filter interface and implement its Dofilter method. For example, the following filter prevents XSS injection.

Xssfilter.java Code:

<span style= "FONT-SIZE:14PX;" >package com.cc;import javax.servlet.*;import Javax.servlet.http.httpservletrequest;import java.io.IOException; public class Xssfilter implements Filter {    filterconfig filterconfig = null;    public void init (Filterconfig filterconfig) throws Servletexception {        this.filterconfig = filterconfig;    }    public void Destroy () {        this.filterconfig = null;    }    public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException,            servletexception {        chain.dofilter (new Xsshttpservletrequestwrapper ((httpservletrequest) request), response);}    } </span>

Xsshttpservletrequestwrapper.java Code:

<span style= "FONT-SIZE:14PX;" >package Com.cc;import Org.springframework.web.util.htmlutils;import javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.httpservletrequestwrapper;public class Xsshttpservletrequestwrapper extends Httpservletrequestwrapper {public xsshttpservletrequestwrapper (HttpServletRequest servletrequest) {super (SERVL    Etrequest);        } public string[] getparametervalues (String parameter) {string[] values = super.getparametervalues (parameter);        if (values = = null) {return null;        } int count = Values.length;        string[] encodedvalues = new String[count];        for (int i = 0; i < count; i++) {Encodedvalues[i] = CLEANXSS (Values[i]);    } return encodedvalues;        public string GetParameter (string parameter) {String value = super.getparameter (parameter);        if (value = = null) {return null;    } return Cleanxss (value); } public StRing GetHeader (string name) {String value = Super.getheader (name);        if (value = = null) return null;    return CLEANXSS (value);    private string Cleanxss (string value) {return Htmlutils.htmlescape (value); }}</span>

Then, use the <filter> and <filter-mapping> elements in the Web. xml file to register the filter class that was written and set the resources it can intercept. Such as:

    <filter>        <filter-name>XssSqlFilter</filter-name>        <filter-class> com.cc.xssfilter</filter-class>    </filter>    <filter-mapping>        <filter-name> xsssqlfilter</filter-name>        <url-pattern>/*</url-pattern>        <dispatcher>request </dispatcher>    </filter-mapping>


<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 full qualified class name of the filter.

The <init-param> element is used to specify the initialization parameters for the filter, its child elements <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 the initialization parameters.

The <filter-mapping> element is used to set a resource that the filter is responsible for intercepting. A filter interception resource can be specified in two ways: the Servlet name and the request path of the resource access

The <filter-name> 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> set the request path blocked by filter (the URL style associated with the filter)

<servlet-name> Specifies the name of the servlet that the filter intercepts.

<dispatcher> specifies how the resource that the filter intercepts is called by the Servlet container, which can be one of Request,include,forward and error, the default request. Users can set multiple <dispatcher> child elements to specify the Filter to intercept multiple calls to the resource. <dispatcher> the values that child elements can set and their meanings:

REQUEST: When the user accesses the page directly, the Web container invokes the filter. If the target resource is accessed through the include () or forward () method of RequestDispatcher, then the filter is not called.

INCLUDE: The filter will be called if the target resource is accessed through the RequestDispatcher include () method. In addition, the filter is not called.

FORWARD: If the target resource is accessed through the RequestDispatcher FORWARD () method, then the filter will be called and the filter will not be called.

Error: If the target resource is called through a declarative exception handling mechanism, then the filter will be called. In addition, the filter is not called.

4. Filter's life cycle.

Filter, like the servlet, is responsible for creating and destroying the Web server. When the Web application starts, the Web server will create an instance object of filter and invoke its init (Filterconfig Filterconfig) method to complete the initialization of the object, thus preparing the interception for subsequent user requests. The filter object is created only once, and the Init method executes only once

The Dofilter method of the filter is called every time the associated Web resource is requested.

Call the Destroy () method before the Web container unloads the Filter object. This method executes only once in the life cycle of the filter. In this method, you can release the resources used by the filter.

When we configure filter, we can use <init-param> to configure some initialization parameters for the filter, when the Web container instantiates the filter object and calls its Init method. The Filterconfig object that encapsulates the filter initialization parameter is passed in. As a result, when writing the filter, the developer can obtain: by Filterconfig the object's method.

String getfiltername (): Gets the name of the filter.

String Getinitparameter (string name): Returns the value of the initialization parameter for the name specified in the deployment description. Returns null if it does not exist.

ServletContext getservletcontext (): Returns the ServletContext object.

two. Listener

Listener's main role is to do some initialization of the content to add work, set up some basic content, such as some parameters or some fixed objects and so on. We can write a Java class that implements the Javax.servlet.ServletContextListener interface, which implements the logic code for the response in this class. When the web app starts, listener will start with it, initialize it, initialize it once, and be destroyed by the Web container when the Web app stops.

For example, the entrance to the implementation of Spring is a listener:

    <listener>        <listener-class>org.springframework.web.context.contextloaderlistener</ Listener-class>    </listener>

three. The load order of Servlets, listener, and filter

The load order of Servlets, listener, and filter is independent of their order in the Web. xml file. It is not registered in the Web. xml file before it will be loaded first, through their respective roles. You can obviously get a conclusion: listener first load, followed by filter, and finally the servlet. However, if Context-param is also configured, it is used to provide ServletContext with key-value pairs, which are application context information. Because of listener, filter and so on initialization will use the information in these contexts, so the Context-param configuration will be loaded first.

For example, the load of the spring configuration file needs to be registered in the Web. xml file:

    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath:spring/spring.xml        </param-value>    </context-param>


Java Web Foundation Summary seven--filter and listener

Related Article

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.