1. 添加監聽
public class SpringContextListener implements ServletContextListener { //獲取spring注入的bean對象 public static WebApplicationContext springContext; public void contextDestroyed(ServletContextEvent event) { //springContext = null; } /** * 獲取spring上下文 */ public void contextInitialized(ServletContextEvent event) { springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); } }
2. 在web.xml中配置監聽
<listener> <listener-class>com.test.util.SpringContextListener</listener-class> </listener>
3. 使用
獲取ServletContext
SpringContextListener.springContext.getServletContext()
獲取webapp路徑
String webPath = SpringContextListener.springContext.getServletContext().getRealPath("");
獲取到的路徑 /usr/local/tomcat/webapps/multimedia
multimedia 是我的項目名稱