[英]Spring Web: Getting file from web context using Resource?
Is there a way to get a resource in a spring web application using a simple Resource? 有没有办法使用简单的资源在Spring Web应用程序中获取资源? I am trying not to pass any context, and need to obtain a file from the WEB-INF/freemarker/email/ directory. 我试图不传递任何上下文,并需要从WEB-INF / freemarker / email /目录中获取文件。
No. Since the WEB-INF/freemaker/email
is not on the classpath, you need to pass ServletContext
. 不可以 。由于WEB-INF/freemaker/email
不在类路径上,因此需要传递ServletContext
。 As you mention Resource
, you can use: 当你提到Resource
,你可以使用:
Resource resource = new ServletContextResource(servletContext, resourcePath);
Just don't pass the ServletContext
to the service layer. 只是不要将ServletContext
传递给服务层。 Pass the Resource
instead. 相反,传递Resource
。
If you want to obtain the template from the classpath, place it there. 如果要从类路径获取模板,请将其放在那里。 That is, for example, in: 也就是说,例如,在:
WEB-INF/classes/freemaker/email WEB-INF /班/ freemaker的/电子邮件
Then you can use ClassPathResource
然后你可以使用ClassPathResource
You can implement org.springframework.context.ResourceLoaderAware interface in your class and get access to ResourceLoader. 您可以在类中实现org.springframework.context.ResourceLoaderAware接口并访问ResourceLoader。 That it's rather easy to use. 这很容易使用。
public class SomeService implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
public void doSomething() {
Resource skin = resourceLoader.getResource("myfile.txt");
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.