天天看點

Servlet Listener 和 Filter

1、Servlet Listener

      共有8個可以實作的監聽器接口,和6種相對應的觸發事件,實作在觸發不同僚件時執行相應的操作。如下

java 代碼

  1. //   
  2. import javax.servlet.ServletRequestEvent;   
  3. import javax.servlet.ServletRequestListener;   
  4. //   
  5. import javax.servlet.ServletRequestAttributeEvent;   
  6. import javax.servlet.ServletRequestAttributeListener;   
  7. //   
  8. import javax.servlet.ServletContextEvent;   
  9. import javax.servlet.ServletContextListener;   
  10. //   
  11. import javax.servlet.ServletContextAttributeEvent;   
  12. import javax.servlet.ServletContextAttributeListener;   
  13. //   
  14. import javax.servlet.http.HttpSessionEvent;   
  15. import javax.servlet.http.HttpSessionListener;   
  16. import javax.servlet.http.HttpSessionActivationListener;   
  17. //   
  18. import javax.servlet.http.HttpSessionBindingEvent;   
  19. import javax.servlet.http.HttpSessionBindingListener;   
  20. import javax.servlet.http.HttpSessionAttributeListener;  

1)、javax.servlet.ServletContextListener

Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
void com.james.webapp.ServletListener.contextInitialized(ServletContextEvent arg0)
Notification that the web application initialization process is starting. All ServletContextListeners are notified of context initialization before any filter or servlet in the web application is initialized.
void com.james.webapp.ServletListener.contextDestroyed(ServletContextEvent arg0)
Notification that the servlet context is about to be shut down. All servlets and filters have been destroy()ed before any ServletContextListeners are notified of context destruction.

2)、javax.servlet.ServletContextAttributeListener

Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

java 代碼

  1. public void attributeAdded(ServletContextAttributeEvent scab);      
  2. public void attributeRemoved(ServletContextAttributeEvent scab);      
  3. public void attributeReplaced(ServletContextAttributeEvent scab);    

3)、javax.servlet.ServletRequestListener

A ServletRequestListener can be implemented by the developer interested in being notified of requests coming in and out of scope in a web component. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain.

java 代碼

  1. public void requestDestroyed ( ServletRequestEvent sre );   
  2. public void requestInitialized ( ServletRequestEvent sre );  

4)、javax.servlet.ServletRequestAttributeListener

A ServletRequestAttributeListener can be implemented by the developer interested in being notified of request attribute changes. Notifications will be generated while the request is within the scope of the web application in which the listener is registered. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain.
Since:
Servlet 2.4

java 代碼

  1.  public void attributeAdded(ServletRequestAttributeEvent srae);   
  2.  public void attributeRemoved(ServletRequestAttributeEvent srae);   
  3.  public void attributeReplaced(ServletRequestAttributeEvent srae);  

5)、javax.servlet.http.HttpSessionListener

Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
Since:
v 2.3

java 代碼

  1. public void sessionCreated ( HttpSessionEvent se );      
  2. public void sessionDestroyed ( HttpSessionEvent se   

6)、javax.servlet.http.HttpSessionActivationListener

Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener. Since: 2.3

java 代碼

  1. public void sessionWillPassivate(HttpSessionEvent se);    
  2. public void sessionDidActivate(HttpSessionEvent se);  

7)、javax.servlet.http.HttpSessionBindingListener

Causes an object to be notified when it is bound to or unbound from a session. The object is notified by an

HttpSessionBindingEvent

object. This may be as a result of a servlet programmer explicitly unbinding an attribute from a session, due to a session being invalidated, or due to a session timing out.
See Also:
HttpSession
HttpSessionBindingEvent

java 代碼

  1. public void valueBound(HttpSessionBindingEvent event);   
  2. public void valueUnbound(HttpSessionBindingEvent event);  

8)、javax.servlet.http.HttpSessionAttributeListener

This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application.
Since:
v 2.3

java 代碼

  1.     public void attributeAdded ( HttpSessionBindingEvent se );   
  2.     public void attributeRemoved ( HttpSessionBindingEvent se );   
  3.     public void attributeReplaced ( HttpSessionBindingEvent se );  

 2、Servlet Filter

      需要實作接口javax.servlet.Filter,下面是一個例子:

java 代碼

  1. import java.io.IOException;   
  2. import javax.servlet.Filter;   
  3. import javax.servlet.FilterChain;   
  4. import javax.servlet.FilterConfig;   
  5. import javax.servlet.ServletException;   
  6. import javax.servlet.ServletRequest;   
  7. import javax.servlet.ServletResponse;   
  8. public class ServerletFilter implements Filter {   
  9.     public void destroy() {   
  10.         // TODO Auto-generated method stub   
  11.     }   
  12.     public void doFilter(ServletRequest arg0, ServletResponse arg1,   
  13.             FilterChain arg2) throws IOException, ServletException {   
  14.         // TODO Auto-generated method stub   
  15.     }   
  16.     public void init(FilterConfig arg0) throws ServletException {   
  17.         // TODO Auto-generated method stub   
  18.     }   
  19. }  

javax.servlet.Filter

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.

Filters perform filtering in the

doFilter

method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.

Filters are configured in the deployment descriptor of a web application

Examples that have been identified for this design are

1) Authentication Filters

2) Logging and Auditing Filters

3) Image conversion Filters

4) Data compression Filters

5) Encryption Filters

6) Tokenizing Filters

7) Filters that trigger resource access events

8) XSL/T filters

9) Mime-type chain Filter

void com.james.webapp.ServerletFilter.destroy()

Called by the web container to indicate to a filter that it is being taken out of service. This method is only called once all threads within the filter's doFilter method have exited or after a timeout period has passed. After the web container calls this method, it will not call the doFilter method again on this instance of the filter.

This method gives the filter an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the filter's current state in memory.

void com.james.webapp.ServerletFilter.doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException
The

doFilter

method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

A typical implementation of this method would follow the following pattern:-

1. Examine the request

2. Optionally wrap the request object with a custom implementation to filter content or headers for input filtering

3. Optionally wrap the response object with a custom implementation to filter content or headers for output filtering

4. a) Either invoke the next entity in the chain using the FilterChain object (

chain.doFilter()

),

4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing

5. Directly set headers on the response after invocation of the next entity in the filter chain.

void com.james.webapp.ServerletFilter.init(FilterConfig arg0) throws ServletException

Called by the web container to indicate to a filter that it is being placed into service. The servlet container calls the init method exactly once after instantiating the filter. The init method must complete successfully before the filter is asked to do any filtering work.

The web container cannot place the filter into service if the init method either

1.Throws a ServletException

2.Does not return within a time period defined by the web container