ServletRuquest监听器
在ServletRequest级别上有3个监听器接口:
ServletRequestListener
ServletRequestAttributeListener
AsyncListener
1. ServletRequestListener
ServletRequestListener对Servlet的创建和销毁做出响应。在Servlet中的通过池来重启ServletRequest的,创建ServletRequest的时间花费相当于从池中获取它的时间,销毁时间则相当于它返回到池的时间。
ServletRequestListener接口定义两个方法
创建ServletRequest是调用:
void requestInitialized(ServletRequestEvent event)
销毁ServletRequest是调用:
void requestDestroyed(ServletRequestEvent event)
例子:
public class ServletRequestTest implements ServletRequestListener{
@Override
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
ServletRequest servletRequest = sre.getServletRequest();
Long start = (Long) servletRequest.getAttribute("start");
Long end = System.nanoTime();
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
StringBuffer uri = httpServletRequest.getRequestURL();
System.out.println("time taken to execute" + uri+":"+((end-start)/1000)+"microseconds");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
// TODO Auto-generated method stub
ServletRequest servletRequest = sre.getServletRequest();
servletRequest.setAttribute("start", System.nanoTime());
}
}
注册
<listener>
<listener-class>listener.ServletRequestTest</listener-class>
</listener>
结果:
2. ServletRequestAttributeListener
每当HttpRequest中添加,删除或替换了某个属性时,ServletRequestAttributeListener的实现都会收到通知,
该监听器接口种有三个方法:
void attributeAdded(HttpRequestBindingEvent event)
void attributeRemoveed(HttpRequestBindingEvent event)
void attributeReplaced(HttpRequestBindingEvent event)
获取属性名和属性值,使用以下两个方法
java.lang.String getName()
java.lang.Object getValue()