示例:自定义监听器:项目一启动就将用户项目路径放到application中,方面页面随时使用。 第一步:创建Maven应用,添加依赖
javax.servlet
javax.servlet-api
4.0.1
org.springframework
spring-context
5.2.5.RELEASE
org.springframework
spring-webmvc
5.2.5.RELEASE
第二步:SpringMVC配置文件
第三步:自定义监听器:
public class ServerStartupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//将web应用名称(路径)保存到application范围中
ServletContext application = sce.getServletContext();
String contextPath = application.getContextPath();
application.setAttribute("APP_PATH", contextPath);
}
}
第四步:web.xml文件:
com.hc.listener.ServerStartupListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:SpringMVC.xml
1
SpringMVC
/
第五步:前端网页:
${pageContext.request.contextPath}
${APP_PATH}
第六步:部署启动应用,假设项目路径为:http://localhost:8080/CustomListener/,结果如下图所示: