你不應該使用FileSystemResource
,你應該使用ServletContextResource
:
new ServletContextResource(servletContext, "/myfile.xml");
假設,當然,前提是ServletContext的是提供給您。
如果你真的想要使用FileSystemResource
,那麼你需要問容器的目錄是哪裏,並使用它作爲相對路徑,例如,
String filePath = servletContext.getRealPath("/myfile.xml");
new FileSystemResource(filePath);
儘管如此,Spring更容易讓你爲你工作。假設你有一個需要這個Resource
的bean。您可以將資源路徑注入爲String,並讓Spring將其轉換爲資源,例如
public class MyBean {
private Resource myResource;
public void setMyResource(Resource myResource) {
this.myResource = myResource;
}
}
,並在你的bean文件:
<bean id="myBean" class="MyBean">
<property name="myResource" value="/path/under/webapp/root/of/my/file.xml">
</bean>
Spring將資源路徑轉換爲ServletContextResource
並傳遞給你的bean。
謝謝!在我的servlet中,我有HttpServletRequest和HttpServletResponse,所以我使用「request.getRealPath()」而不是servletContext.getRealPath()。 – portoalet 2010-03-04 14:36:35
救了我的命! – rpr 2011-07-23 21:45:03