Spring MVC在没有请求的情况下获取WEB-INF下的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11210465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:11:55  来源:igfitidea点击:

Spring MVC Get file under WEB-INF without a request

springspring-mvc

提问by mmm

I am trying to get hold of a file ( or a directory ) under /WEB-INF/.../

我正在尝试获取下的文件(或目录) /WEB-INF/.../

outside of a request. I need it in a bean loaded at server startup.

在请求之外。我需要在服务器启动时加载的 bean 中使用它。

All solutions I can find either wants an XML file using ClassPathXmlApplicationContextor a request to get the servlet context or using the current executing class. Seems ugly to me.

我能找到的所有解决方案要么需要使用 XML 文件,要么ClassPathXmlApplicationContext需要获取 servlet 上下文或使用当前执行类的请求。在我看来很难看。

How can I get a File("/WEB-INF/myDir/"). There has to be a way, no!?

我怎样才能得到一个File("/WEB-INF/myDir/"). 总得有个办法吧!?

回答by axtavt

As long as your bean is declared in web application context you can obtain an instance of ServletContext(using ServletContextAware, or by autowiring).

只要您的 bean 在 Web 应用程序上下文中声明,您就可以获得ServletContext(使用ServletContextAware,或通过自动装配)的实例。

Then you can access files in webapp directory either directly (getResourceAsStream(), getRealPath()), or using ServletContextResource.

然后,您可以直接 ( getResourceAsStream(), getRealPath()) 或使用ServletContextResource.

EDIT by momo:

由莫莫编辑:

@Autowired
ServletContext servletContext;

... myMethod() { 
     File rootDir = new File( servletContext.getRealPath("/WEB-INF/myDIR/") );
}

回答by mahesh nanayakkara

I use SpringDefaultResourceLoaderand Resourceto read inside WEB-INF or any resources in a *.jar file. Work like a charm. Good luck!

我使用Spring DefaultResourceLoaderResource来读取 WEB-INF 或 *.jar 文件中的任何资源。像魅力一样工作。祝你好运!

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

public static void myFunction() throws IOException {
    final DefaultResourceLoader loader = new DefaultResourceLoader();               
    LOGGER.info(loader.getResource("classpath:META-INF/resources/img/copyright.png").exists());             
    Resource resource = loader.getResource("classpath:META-INF/resources/img/copyright.png");           
    BufferedImage watermarkImage = ImageIO.read(resource.getFile());
}

回答by Murali Krish

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("files/test.xml").getFile());

"files" folder should be child of "main/resources" folder

“files”文件夹应该是“main/resources”文件夹的子文件夹

回答by NimChimpsky

You can use classpath resource if the file is located in the WEB_INF\classesdirectory. Which is where any files in your src/main/resourcesdirectory will be copied to using a normal maven build ...

如果文件位于WEB_INF\classes目录中,则可以使用类路径资源。这是您src/main/resources目录中的任何文件将被复制到使用普通 maven 构建的地方...

import org.springframework.core.io.Resource
...
final Resource yourfile = new ClassPathResource( "myfile.txt");

回答by ACV

This is how you can do it if you just want to access it from a Service (not through ServletContext):

如果您只想从服务(而不是通过 ServletContext)访问它,您可以这样做:

    final DefaultResourceLoader loader = new DefaultResourceLoader();
    Resource resource = loader.getResource("classpath:templates/mail/sample.png");
    File myFile = resource.getFile();

Note that the last line may throw IOExceptionso you need to catch / rethrow

请注意,最后一行可能会抛出,IOException因此您需要捕获/重新抛出

Note, that the file is here: src\main\resources\templates\mail\sample.png

请注意,该文件在这里: src\main\resources\templates\mail\sample.png

回答by Kirill

Not completely related to your question, but... Here is some universal sulution i used to load properties from anywhere in web application like Spring does it (supporting WEB-INF/..., classpath:..., file:...). Is is based on using ServletContextResourcePatternResolver. You will need ServletContext.

与您的问题不完全相关,但是...这是一些通用的解决方案,我用来从 Web 应用程序中的任何位置加载属性,就像 Spring 一样(支持 WEB-INF/..., classpath:..., file:.. .) 是基于使用ServletContextResourcePatternResolver. 您将需要ServletContext.

private static Properties loadPropsTheSpringWay(ServletContext ctx, String propsPath) throws IOException {
    PropertiesFactoryBean springProps = new PropertiesFactoryBean();
    ResourcePatternResolver resolver = new ServletContextResourcePatternResolver(ctx);
    springProps.setLocation(resolver.getResource(propsPath));
    springProps.afterPropertiesSet();
    return springProps.getObject();
}

I used the above method in my custom servlet context listener while conext was not yet loaded.

我在我的自定义 servlet 上下文侦听器中使用了上述方法,而 conext 尚未加载。

回答by gene b.

request.getSession().getServletContext().getResourceAsStream("yourfile.pdf");