Listener and filter in Servlet

Source: Internet
Author: User
Tags object serialization

From: http://ruowu.iteye.com/blog/661922

Listener I understand him in this way. It is an observer mode implementation: We are in the web. when listener is configured in XML, an observer is placed in the observer's observation object queue. When the observer triggers the registration event, the observer responds accordingly. The specific implementation in JSP/servlet is to register listener in Web. XML, and the container calls a specific class to implement listener when a specific event occurs.

In general, Servlet has three main types of events: servlet context events, session events and request events a total of eight listener (part of the content is reproduced in the http://ritaleo.javaeye.com/blog/48751) interface, we in the web. when registering in XML, You can implement the corresponding interface class:

Listener and event in servlet:

1. In JSP 2.0/servlet 2.4, there are eight listener interfaces and six event categories.
Servletcontextlistener Interface
[Interface method] contextinitialized () and contextdestroyed ()
[Receive events] servletcontextevent
[Trigger scenario] contextinitialized () is called when the container loads a web application (for example, after the container is started), and The contextdestroyed () method is called when the container removes the web application.

2. servletcontextattributelistener
[Interface method] attributeadded (), attributereplaced (), attributeremoved ()
[Receive events] servletcontextattributeevent
[Trigger scenario] if an object is added as the attribute of the application (servletcontext) object, attributeadded () is called. Similarly, attributereplaced () is called when attributes are replaced or removed () attributeremoved ().

3. httpsessionlistener
[Interface method] sessioncreated () and sessiondestroyed ()
[Receive events] httpsessionevent
[Trigger scenario] When a session (httpsession) object is created or eliminated, the two methods are called respectively.

4. httpsessionattributelistener
[Interface method] attributeadded (), attributereplaced (), attributeremoved ()
[Receive events] httpsessionbindingevent
[Trigger scenario] if an object is added as the attribute of the session (httpsession) object, attributeadded () is called. Similarly, attributereplaced () is called when the attribute is replaced or removed () attributeremoved ().

5. httpsessionactivationlistener
[Interface method] sessiondidactivate () and sessionwillpassivate ()
[Receive events] httpsessionevent
[Trigger scenario] Activate and passivate are actions used to replace objects, when the session object must be temporarily stored to the hard disk or other storage devices for reasons such as resource utilization or load balancing (through object serialization), the action is called passivate, the Session object on the hard disk or storage device is called activate when the JVM is reloaded. It is easy to understand that sessiondidactivate () and sessionwillpassivate () call after activeate and before passivate respectively.

6. servletrequestlistener
[Interface method] requestinitialized () and requestdestroyed ()
[Receive events] requestevent
[Trigger scenario] the two methods are called when the request (httpservletrequest) object is created or eliminated.

7. servletrequestattributelistener
[Interface method] attributeadded (), attributereplaced (), attributeremoved ()
[Receive events] httpsessionbindingevent
[Trigger scenario] if an object is added as an attribute of the request (httpservletrequest) object, attributeadded () is called. Similarly, attributereplaced () is called when attributes are replaced or removed () attributeremoved ().

8. httpsessionbindinglistener
[Interface method] valuebound () and valueunbound ()
[Receive events] httpsessionbindingevent
[Trigger scenario] class for implementing the httpsessionbindinglistener interface. For example, if it is added to the attribute of the session (httpsession) object, valuebound () is called. If it is removed from the session (httpsession) when you remove an object from its attributes, the system calls valueunbound () to implement the httpsessionbindinglistener interface. set in XML.

Specific usage: Add the following statement to Web. xml:

< listener >  < listener-class > com.servlet.listener.YouAchieveListener  < \listener-class >< \listener >

Among them, youachievelistener is the implementation class of a listener interface implemented by you. com. servlet. Listener is your package name.

Filter: filter technology is a new servlet 2.3 function)

Filter allows you to change a request or modify a response. A filter is not a servlet. It cannot generate a response, but it can process the request before a request arrives at the servlet. It can also process the response when a response leaves the servlet.

A filter includes:
1. intercepted before the servlet is called;
2. Check the Servlet request before the servlet is called;
3. Modify the request header and request data as needed;
4. Modify the response header and response data as needed;
5. After the servlet is called, it is intercepted.

The correspondence between filters and servlets is many-to-many. That is to say, you can configure one filter to one or more Servlets, and one servlet can have multiple filters. Some useful filters include: User Identification filter, LOG filter, audit filter, encryption filter, symbol filter, and XSLT filter that can change XML content.
A filter must implement the javax. servlet. Filter interface and define three methods:
1. Void setfilterconfig (filterconfig config) // sets the configuration object of the filter;
2. filterconfig getfilterconfig () // return the configuration object of the filter;
3. Void dofilter (servletrequest req, servletresponse res, filterchain chain) // executes the filter operation.

The server only calls the setfilterconfig method once to prepare the filter processing. The dofilter method is called multiple times to process different requests. you can find the Filter Name and initialization parameter information through the filterconfig interface. the server can set filterconfig to null to indicate that the filter has ended.
Each filter obtains the current request and response from the dofilter () method. in this method, you can perform any request and response operations. (including data collection and packaging ). filter calls chain. the dofilter () method gives control to the next filter. A filter ends in the dofilter () method. if a filter wants to stop request processing and get full control over response, it can not call the next filter.
A filter can wrap request or response to change several methods and provide custom attributes. api2.3 provides httpservletrequestwrapper and httpservletresponsewrapper. they can dispatch the initial request and response. to change the features of a method, you must inherit the wapper and override methods. below is a simple LOG filter used to record the duration of all requests.

public class LogFilter implements Filter { FilterConfig config; public void setFilterConfig(FilterConfig config) { this.config = config; } public FilterConfig getFilterConfig() { return config; } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) { ServletContext context = getFilterConfig().getServletContext(); long bef = System.currentTimeMillis(); chain.doFilter(req, res); // no chain parameter needed here long aft = System.currentTimeMillis(); context.log("Request to " + req.getRequestURI() + ": " + (aft-bef)); } } 

When the server calls setfilterconfig (), the filter saves the config information. use the config information in the dofilter () method to obtain the servletcontext. to run this filter, you must configure it to the Web. in XML. take tomcat4.01 as an example:

<Filter> <filter-Name> log // Filter Name </filter-Name> <filter-class> logfilter // filter class (servlet in the previous example) </filter-class> </filter> <filter-mapping> <filter-Name> log </filter-Name> <servletname> servletname </servlet-Name> </Filter -Mapping> <servlet-Name> servletname </servletname> <servletclass> servletclass </servlet-class> </servlet> <servlet-mapping> <servlet-Name> servletname </servlet-Name> <URL-pattern> * </url-pattern> </servlet-mapping>

From the above example, we can see that the filter and Servlet are configured in Web. xml.

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.