多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
![](https://box.kancloud.cn/c4ef112f62b1c045340893b1ffc823a0_343x355.png) 监听器FirstServletContextAttributeListener.java ~~~ package zyw; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.annotation.WebListener; @WebListener public class FirstServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) { System.out.println("属性被添加"); System.out.println(servletContextAttributeEvent.getName());//属性名称 System.out.println(servletContextAttributeEvent.getValue());//属性的值 } @Override public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) { System.out.println("属性被删除"); System.out.println(servletContextAttributeEvent.getName());//获取属性的名称 System.out.println(servletContextAttributeEvent.getValue());//获取属性的值 } //属性被修改的时候出发这个方法 @Override public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) { System.out.println("属性被修改"); System.out.println(servletContextAttributeEvent.getName());//获取属性的名称(修改前的值) System.out.println(servletContextAttributeEvent.getValue());//获取属性的值(修改前的值) } } ~~~ TestAttributeListenerServlet.java ~~~ package zyw.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "TestAttributeListenerServlet",urlPatterns = "/test") public class TestAttributeListenerServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext = request.getServletContext(); servletContext.setAttribute("name","zhangsan");//触发监听器增加的方法 servletContext.setAttribute("name","lisi");//触发监听器修改的方法 servletContext.removeAttribute("name");//触发监听器删除的方法 } } ~~~ ![](https://box.kancloud.cn/ae760bb89e0bfe77bd93a3aa718b0a06_1026x223.png)