我通過使用下面的代碼獲取上下文路徑。春季獲取上下文路徑而不依賴於servlet
String contextpath = request.getSession().getServletContext().getRealPath("sample.html");
但正如我的代碼是在業務方面,我在這裏使用唯一的方法傳遞file name
,根據我需要在服務器戰爭的文件夾,我怎麼能得到它的路徑文件名?
我正在使用spring web應用程序。
我通過使用下面的代碼獲取上下文路徑。春季獲取上下文路徑而不依賴於servlet
String contextpath = request.getSession().getServletContext().getRealPath("sample.html");
但正如我的代碼是在業務方面,我在這裏使用唯一的方法傳遞file name
,根據我需要在服務器戰爭的文件夾,我怎麼能得到它的路徑文件名?
我正在使用spring web應用程序。
我們需要服務/ dao /資源層中的實際路徑來做很多事情。在Web應用程序初始化時提取該路徑並將其存儲在系統所有層可以訪問的地方是個好主意。
做到這一點的一種方法是通過ServletListener接口。以下是正確顯示如何操作的鏈接。
在Spring應用程序中,最好將它存儲在注入式bean中... –
對於Spring應用程序,你可以只使用一個應用程序上下文感知豆。由於應用程序是一個Web應用程序,在ApplicationContext將是一個WebApplicationContext
,所以你可以要求它爲ServletContext中:
public class ContextPathHolder
implements ApplicationContextAware, InitializingBean {
private WebApplicationContext wac;
private String contextPath;
private String realPath;
public void setApplicationContext(ApplicationContext ac) {
wac = (WebApplicationContext) ac;
}
public void afterPropertiesSet() {
ServletContext sc = wac.getServletContext();
contextPath = sc.getContextPath();
realPath = sc.getRealPath();
}
public String getContextPath() {
return contextPath;
}
public String getRealPath() {
return realPath;
}
}
這樣的話,你有一個簡單的bean,你可以在任何其他的bean,將需要注入servlet上下文路徑。
用法示例假設xml配置:
服務類需要訪問真正的上下文路徑:
class ConfigurableServiceImpl implements ConfigurableService {
private ContextPathHolder pathHolder;
public setPathHolder(ContextPathHolder pathHolder) {
this.pathHolder = pathHolder;
}
@Override
public MyServiceObject myServiceMethod(...) {
String realContextPath = pathHolder.getRealPath(); // get the real path...
...
}
的Spring XML根上下文
<bean id="contextWebApplicationContextProvider" class="...ResourcePathHolder"/>
<bean id="configurableService" class="...ConfigurableServiceImpl"
p:pathHolder="contextWebApplicationContextProvider">
...
</bean>
你可以寫ServletListener並設置一些在應用程序中的靜態值 –
@Sangram Jadhav你可以用代碼顯示我。 – dafodil
[獲取上下文路徑(沒有HttpRequest)](http://jblewitt.com/blog/?p=365) –