The listener's role in the following:
After when the web service starts, and created servletContext domain object will get the web has a virtual path, and save servletContext domain object, so you can get a virtual path across the web directly from the application domain
Code:
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 { /** * Immediate execution method when contextInitialized ServletContext domain creation * / @Override public void contextInitialized (ServletContextEvent SCE) { // get servletContext domain ServletContext servletContext = sce.getServletContext (); // Gets the virtual path String contextPath = servletContext.getContextPath (); / / path into domain servletContext.setAttribute ( " path " , the contextPath); } @Override public void the contextDestroyed (ServletContextEvent SCE) { // the TODO Auto-Generated Method Stub } }
Profiles:
<listener> <listener-class>com.servlet.ServletListner</listener-class> </listener>