Summary of Listener (listener) and filter in servlet

Source: Internet
Author: User
Tags object serialization

Listener I understand him this way, he is the realization of an observer pattern: When we configure Listener in Web. XML, it is the observer queue that puts an observer into the viewer, and the observer responds accordingly when the observed person triggers the registration event. The specific implementation in Jsp/servlet is to register Listener in Web. XML, which is called by Container to call a specific implementation Listener class when a particular event occurs.

In general, there are 3 main types of events in the servlet: Servlet context Event, session event, and request event total 8 Listener (part classification volume reproduced in http://ritaleo.javaeye.com/blog/48751) interface, we When registering with Web. XML, it corresponds to its own implementation class for the corresponding interface:

Listener and Event in the Servlet:

1.          in  jsp 2.0/servlet 2.4 , a total of eight  listener   Interface, six  Event  categories.  
servletcontextlistener  interface  
[  interface Method  ] contextinitialized ()     Contextdestroyed ()  
[  receive event  ] servletcontextevent 
[  trigger Scene  ]  in   container  when loading  Web  application (for example, after startup  Container ),  contextinitialized ()   is called, and when the container is removed  Web  application, the  contextdestroyed ()   method is called.

2. Servletcontextattributelistener
[Interface Method] Attributeadded (), attributereplaced (), attributeremoved ()
[Receive event] Servletcontextattributeevent
[Trigger scene] If an object is added as a property of the application (ServletContext) object, it will call Attributeadded (), as in the case of the displacement property and the Remove attribute, respectively call attributereplaced (), attr Ibuteremoved ().

3. Httpsessionlistener
[Interface Method] Sessioncreated () and sessiondestroyed ()
[Receive event] Httpsessionevent
[Trigger scene] when the session (HttpSession) object is established or destroyed, the two methods are called separately.

4.         httpsessionattributelistener 
[  interface method  ] attributeadded ()  ,  attributereplaced ()  ,  attributeremoved ()  
[  receive events  ] httpsessionbindingevent 
[  trigger Scene  ]  If an object is added as  session  ( httpsession  ) object, the  attributeadded ()   is called, as is the case when the displacement property and the Remove attribute are called  attributereplaced ()  ,   Attributeremoved ()  .

5. Httpsessionactivationlistener
[Interface Method] Sessiondidactivate () and Sessionwillpassivate ()
[Receive event] Httpsessionevent
[Trigger Scene] Activate and Passivate are actions that are used to displace objects, and when the session object must be stored temporarily on a hard disk or other storage for reasons such as resource utilization or load balancing (through object serialization), the action is called Passivate, The action taken by the session object on the hard disk or the storage device to reload the JVM is called Activate, so it is easy to understand that sessiondidactivate () and Sessionwillpassivate () are after activeate with P Assivate before the call.

6. Servletrequestlistener
[Interface Method] Requestinitialized () and requestdestroyed ()
[Receive event] Requestevent
[Trigger scene] when the request (HttpServletRequest) object is established or destroyed, the two methods are called separately.

7.         servletrequestattributelistener 
[  interface method  ] attributeadded ()  ,  attributereplaced ()  ,  attributeremoved ()  
[  Receive event  ] httpsessionbindingevent 
[  trigger Scene  ]  If an object is added as  request  (  httpservletrequest ) object, the  attributeadded ()   is called, in the same vein when the displacement property and the Remove attribute are called  attributereplaced ()  ,  attributeremoved ()  .

8. Httpsessionbindinglistener
[Interface Method] Valuebound () and Valueunbound ()
[Receive event] Httpsessionbindingevent
[Trigger scenario] implements the class of the Httpsessionbindinglistener interface, and its instance is called Valuebound () if it is added to the properties of the session (HttpSession) object, if it is removed from the session (Ht Tpsession) object, the class that implements the Httpsessionbindinglistener interface is called Valueunbound () and does not need to be set in Web. Xml.

How to use: Add the following statement to Web. XML:

< listener >
< Listener-class > Com.servlet listener. Youachievelistener </listener-class >

</listener >

Where Youachievelistener is the implementation class Com.servlet for one of the Listener interfaces you implement. Listener. The name of your package.

Filter:filter technology is a new feature added to Servlet 2.3. (The following part of the class is reproduced in http://www.programfan.com/article/1836.html)

The user of Filter can change a request or modify a response. Filter is not a servlet, it cannot produce a response, but he can pre-process the request before a request arrives at the servlet, or it can handle response when a response leaves the servlet.

A filter includes:
1. Intercept before the servlet is invoked;
2. Check the servlet request before the servlet is invoked;
3. Modify the request header and request data as required;
4. Modify the response head and response data as required;
5. Intercepted after the servlet is invoked.

The corresponding relationship between the filter and the servlet is a many-to-many relationship, meaning you can configure a filter to one or more servlets; And a servlet can have multiple filter. Several useful filter elements include: User identification filter, log filter, audit filter, encryption filter, symbol filter, XSLT filter that can change XML content, and so on.
A filter must implement a Javax.servlet.Filter interface and define three methods:
1.void setfilterconfig (filterconfig config)//Set Filter configuration object;
2. Filterconfig getfilterconfig ()//Returns the configuration object of filter;
3. void DoFilter (ServletRequest req, servletresponse Res, filterchain chain)//Perform the work of filter.

The server only calls the Setfilterconfig method one time to prepare the filter processing; Call the DoFilter method multiple times to handle different requests. The Filterconfig interface has methods to find the filter name and initialization parameter information. The server can set Filterconfig to NULL to indicate that the filter has been terminated.
Each filter gets the current request and response from the DoFilter () method. In this method, you can do any action for request and response. (including collecting data, packing data, etc.). The filter invokes the Chain.dofilter () method to give control to the next filter. A filter ends in the DoFilter () method. If a filter wants to stop the request processing and get full control of the response, it can not invoke the next filter.
A filter can wrap a request or response to change several methods and provide user-customized properties. Api2.3 provides httpservletrequestwrapper and httpservletresponsewrapper to achieve this. They can dispatch the original request and response. If you want to change the attributes of a method, you must inherit the Wapper and override methods. Here is a simple log filter to record the duration of all the request.

?
12345678910111213141516171819202122 publicclassLogFilter implementsFilter { FilterConfig config; publicvoidsetFilterConfig(FilterConfig config) { this.config = config; public FilterConfig getFilterConfig() { returnconfig; publicvoiddoFilter(ServletRequest req, ServletResponse res, FilterChain chain) { ServletContext context = getFilterConfig().getServletContext(); longbef = System.currentTimeMillis(); chain.doFilter(req, res); // no chain parameter needed here longaft = System.currentTimeMillis(); context.log("Request to "+ req.getRequestURI() ": "+ (aft-bef)); }

When the server calls Setfilterconfig (), filter saves the config information. ServletContext is obtained through the config information in the DoFilter () method. If you want to run this filter, you must configure it to Web. Xml. Take tomcat4.01 as an example:

?
1234567891011121314151617181920 <filter> <filter-name> log //filter 名字 </filter-name> <filter-classLogFilter //filter class( 上例的 servlet) </filter-class</filter> <filter-mapping> <filter-name>log</filter-name> <servletname>servletname</servlet-name> </filter-mapping> <servlet> <servlet-name>servletname</servletname> <servletclass>servletclass</servlet-class</servlet> <servlet-mapping> <servlet-name>servletname</servlet-name> <url-pattern>*</url-pattern> </servlet-mapping>

As can be seen from the above example, the filter and servlet are configured in Web. Xml.

Original source: http://my.oschina.net/ydsakyclguozi/blog/398403

Summary of Listener (listener) and filter in servlet

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.