在spring的bean中獲取ServletContext 和 servletConfig
常規(guī)方式下獲取servletContext需要繼承HttpServlet類,然后獲取servletConfig,通過這個(gè)獲取servletContext(servletConfig.getServletContext())。
但是spring的bean都是pojo,和我們常規(guī)的操作有些不同。
spring給我們提供了兩個(gè)接口:org.springframework.web.context.ServletContextAware和org.springframework.web.context.ServletConfigAware。我們可以讓我們的bean實(shí)現(xiàn)上邊的任何一個(gè)接口就能獲取到servletContext了 .
代碼如下:
public class DicBean implements ServletContextAware{
private ServletContext servletContext;
public void setServletContext(ServletContext sc) {
this.servletContext=sc;
System.out.println("項(xiàng)目應(yīng)用的絕對路徑為:"+servletContext.getRealPath("/"));
}
}
posted on 2011-06-18 09:44
紫蝶∏飛揚(yáng)↗ 閱讀(2811)
評論(0) 編輯 收藏 所屬分類:
Spring 、
重點(diǎn) 、
JSP