假设已经配置好java,tomcat环境
创建AppListener.java文件
import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class AppListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { } @Override public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext() ; Map<String, String> countries = new HashMap<String, String>(); countries.put("ca", "Canada"); countries.put("us", "United States"); servletContext.setAttribute("countries", countries); } }
编译将.class文件放于apache-tomcat-9.0.6(Tomcat安装目录)\webapps\ROOT\WEB-INF\classes下,在WEB-INF\web-xml中添加
<listener> <listener-class>AppListener</listener-class> </listener>
父标签为web-app
创建countries.jsp文件
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>Country List</title> </head> <body> We operate in these countries: <ul> <c:forEach items="${countries}" var="country"> <li>${country.value}</li> </c:forEach> </ul> </body> </html>
保存于\ROOT\jsp中(jsp文件夹自己添加)
添加jstl-1.2.jar和javax.servlet-api-4.0.1.jar到\ROOT\WEB-INF\lib中
启动tomcat
浏览器输入http://localhost:8080/jsp/countries.jsp
可以看到
此方法只为过一把成功的瘾,具体原理和教程自行百度。