[b] 我的需求是擷取 ServletContext ,以擷取Attribute中的變量,在頁面application也可以擷取[/b]
參考一下的文章
進而引申到我需要知道servletContext,因為servletContext有一個servletContext.getRealPath("/");方法,這個方法就能擷取項目的絕對路徑。
正常方式下我們如何擷取servletContext呢?我們需要讓我們的類繼承HttpServlet類,然後擷取servletConfig,通過這個擷取servletContext(servletConfig.getServletContext())。(至于如何擷取servletconfig對象,大家去google,百度找找吧)
但是我需要在spring的bean中直接擷取,這下可和我們正常的操作有些不同,因為spring的bean都是pojo的。根本見不着servletconfig和servletcontext的影子。
這裡我需要指出spring給我們提供了兩個接口:org.springframework.web.context.ServletContextAware和
org.springframework.web.context.ServletConfigAware。我們可以讓我們的bean實作上邊的任何一個接口就能擷取到servletContext了 .
代碼如下:
view plaincopy to clipboardprint?
public class DicBean implements ServletContextAware{
private ServletContext servletContext;
public void setServletContext(ServletContext sc) {
this.servletContext=sc;
System.out.println("項目的絕對路徑為:"+servletContext.getRealPath("/"));
}
}
public class DicBean implements ServletContextAware{
private ServletContext servletContext;
public void setServletContext(ServletContext sc) {
this.servletContext=sc;
System.out.println("項目的絕對路徑為:"+servletContext.getRealPath("/"));
}
}
這樣,我們的bean就能夠直接擷取到servletContext了
如果你想要servletConfig,那方法一樣,隻是實作的接口不同了。
原理推想:應該是在建立spring的sessionFactory的時候,将應用伺服器的相關屬性一并加載[url],檢視建立的bean是否實作相關接口,如果實作了,就将相關值賦予bean。
來自:[url]http://www.zoomhoo.com/viewthread.jsp?tid=121[/url]