与请求相关的监听器
概述
与请求相关的监听器有三个:ServletRequestListener、ServletRequestAttributeListener与AsyncListener。第三个是在Servlet 3.0中新增的监听器。
ServletRequestListener
ServletRequestListener是“生命周期监听器”,如果想要在HttpServletRequest对象生成或结束时做些相对应的操作,则可以实现ServletRequestListener。在ServletRequest对象初始化后或销毁前,会调用requestInitialized()与requestDestroyed()方法,并传入ServletRequestEvent,通过它可以取得ServletRequest,以针对请求对象做出相对应的初始化或结束处理动作。
声明
方法一:在实现ServletRequestListener的类上标注@WebListener
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@WebListener() public class SomeRequestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { // ... } @Override public void requestInitialized(ServletRequestEvent sre) { //... } }
方法二:在web.xml中声明
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<web-app...> ... <listener> <listener-class>cc.openhome.SomeRequestListener</listener-class> </listener> ... <web-app>
ServletRequestAttributeListener
ServletRequestAttributeListener是“属性改变监听器”,在请求对象中加入属性、移除属性或替换属性时,相对应的attributeAdded()、attributeRemoved()与attributeReplaced()方法就会被调用,并分别传入ServletRequestAttributeEvent。ServletRequestAttributeEvent有个getName()方法,可以取得属性设置或移除时指定的名称,而getValue()则可以取得属性设置或移除时的对象。
声明
方法一:在实现ServletRequestAttributeListener的类上标注@WebListener
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@WebListener() public class SomeRequestAttrListener implements ServletRequestAttributeListener { @Override public void attributeAdded(ServletRequestAttributeEvent srae) { //... } @Override public void attributeRemoved(ServletRequestAttributeEvent srae) { //... } @Override public void attributeReplaced(ServletRequestAttributeEvent srae) { //... } }
方法二:在web.xml中声明
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<web-app...> ... <listener> <listener-class>cc.openhome.SomeRequestAttrListener</listener-class> </listener> ... <web-app>