在ServletContext级别上有两个监听器接口:ServletContextListener和ServletContextAttributeListener
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>效果:
