在spring中获取上下文路径而不依赖servlet
我使用下面的代码获取上下文路径在spring中获取上下文路径而不依赖servlet,spring,url,web,Spring,Url,Web,我使用下面的代码获取上下文路径 String contextpath = request.getSession().getServletContext().getRealPath("sample.html"); 但由于我的代码在业务端,我在这里使用唯一的方法来传递文件名,根据文件名,我需要获取服务器中war文件夹的路径。我如何获取它 我正在使用SpringWeb应用程序。我们需要在服务/dao/资源层中使用真实路径来完成许多事情。在初始化web应用程序时提取该路径,并将其存储在系统所有层都可
String contextpath = request.getSession().getServletContext().getRealPath("sample.html");
但由于我的代码在业务端,我在这里使用唯一的方法来传递文件名
,根据文件名,我需要获取服务器中war文件夹的路径。我如何获取它
我正在使用SpringWeb应用程序。我们需要在服务/dao/资源层中使用真实路径来完成许多事情。在初始化web应用程序时提取该路径,并将其存储在系统所有层都可以访问的地方,这是一个好主意 一种方法是通过ServletListener接口。下面是一个链接,它确切地展示了如何做
对于Spring应用程序,您可以只使用应用程序上下文感知bean。由于应用程序是一个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,可以将它注入到任何需要servlet上下文路径的其他bean中
假设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...
...
}
SpringXML根上下文
<bean id="contextWebApplicationContextProvider" class="...ResourcePathHolder"/>
<bean id="configurableService" class="...ConfigurableServiceImpl"
p:pathHolder="contextWebApplicationContextProvider">
...
</bean>
...
您可以编写ServletListener并在中设置一些静态值application@SangramJadhav你能用代码给我看一下吗?@Sangram Jadhav ServletContextInfo在这个属性文件中,我需要放一些getter和setter。请帮助我,我是Java的新手,如何在我使用过的其他classin applicationcontext.xml的方法中调用realPath我使用了字符串contextPath=applicationContext.afterPropertiesSet().realPath;在类的某个方法中,但在ApplicatContext和显示错误后,我不会得到任何intilej。请您解释应该做什么或如何做?您的专有解决方案仍然需要ServletContext:-/