Servlet3.0作为J2EE 6规范一部分,并随J2EE6一起发布,@WebListener是该注解用于将类声明为监听器,是Servlet3.0的新特性,不需要在web.xml进行配置,简化了配置。
一、Listener介绍
在servlet3.0以后,我们可以不用再web.xml里面配置listener,只需要加上@WebListener注解就可以实现。
二、@WebListener用法
该注解用于将类声明为监听器,被 @WebListener 标注的类必须实现以下至少一个接口:
- ServletContextListener
- ServletContextAttributeListener
- ServletRequestListener
- ServletRequestAttributeListener
- HttpSessionListener
- HttpSessionAttributeListener
下面是@WebListener的属性列表。
Name | Type | Required | Description |
value | String | Optional | Description of the listener. |
示例:
package com.dxz.demo.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("application started");
}
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("application stopped");
}
}
package com.dxz.demo.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener("Session listener for the application")//description of the listener
public class MySessionListener implements HttpSessionListener, HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
}
@Override
public void sessionCreated(HttpSessionEvent event) {
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
}
}
结果:
注意:
1、Listener类使用@WebListener注解;
2、Spring boot的启动类需要增加@ServletComponentScan用于扫描加载Listener类;