下面这个监听器的作用:
当web服务启动时,并创建了servletContext域对象后,会取得这个web已用的虚拟路径,并保存在servletContext域对象中,这样就可以在整个web应用中直接从域中获取虚拟路径
代码:
package com.servlet; import java.io.IOException; import java.util.Date; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * ServletContext生死监听器 */ //@WebServlet("/SecondServlet") public class ServletListner implements ServletContextListener { /** * ServletContext域创建时立即执行contextInitialized方法 */ @Override public void contextInitialized(ServletContextEvent sce) { //获取servletContext域 ServletContext servletContext = sce.getServletContext(); //获取虚拟路径 String contextPath = servletContext.getContextPath(); //将路径存入域中 servletContext.setAttribute("path", contextPath); } @Override public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } }
配置文件:
<listener> <listener-class>com.servlet.ServletListner</listener-class> </listener>