Servlet 监听器----Servlet Context

xiaoxiao2021-02-28  111

Servlet Context监听器

在ServletContext级别上有两个监听器接口:ServletContextListener和ServletContextAttributeListener

1.ServletContextListener

ServletContextListener会对ServletContext的初始化和解构做出响应。 ServletContext被初始化时,Servlet容器会在所有已经注册的ServletContextListener中调用contextInitialized() 当ServletContext要被解构和销毁时,Servlet容器会在所有已经注册的ServletContextListener中调用contextDestroyed(), contextInitialized和contextDestroyed都会接收到一个来自Servlet的ServletContextEvent。

实例

Java类

public class AppListener implements ServletContextListener{ @Override public void contextDestroyed(ServletContextEvent sce) { } @Override public void contextInitialized(ServletContextEvent sce) { // TODO Auto-generated method stub ServletContext servletContext = sce.getServletContext(); Map<String, String> countries = new HashMap<String, String>(); countries.put("ca", "canada"); countries.put("ch", "China"); servletContext.setAttribute("countries", countries); } } contextInitialized的代码实现。 首先在Servlet传递的ServletContextEvent中调用getServletContext方法,然后再创建一个Map,填入两个值,把Map作为ServletContext的属性

在部署描述符上注册监听

<listener> <listener-class>listener.AppListener</listener-class> </listener>

使用

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Country List</title> </head> <body> List: <ul> <c:forEach items="${countries }" var="country"> <li>${country.value }</li> </c:forEach> </ul> </body> </html>

效果:

2.ServletContextAttributeListener

每当ServletContext中添加,删除或替换了某个属性时,ServletContextAttributeListener的实现都会收到通知, 该监听器接口种有三个方法: void attributeAdded(ServletContextAttributeEvent event) void attributeRemoveed(ServletContextAttributeEvent event) void attributeReplaced(ServletContextAttributeEvent event) 获取属性名和属性值,使用以下两个方法 java.lang.String getName() java.lang.Object getValue()
转载请注明原文地址: https://www.6miu.com/read-83007.html

最新回复(0)