Spring MVC在没有请求的情况下在WEB-INF下获取文件 [英] Spring MVC Get file under WEB-INF without a request

查看:269
本文介绍了Spring MVC在没有请求的情况下在WEB-INF下获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存/WEB-INF/.../

.我需要在服务器启动时加载的Bean中使用它.

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

我可以找到的所有解决方案都需要使用ClassPathXmlApplicationContext的XML文件,或者是获取servlet上下文的请求,或者是使用当前正在执行的类.对我来说似乎很丑.

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

如何获取File("/WEB-INF/myDir/").必须有一种方法,没有!?

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

推荐答案

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

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

然后,您可以直接(getResourceAsStream()getRealPath())或使用ServletContextResource访问webapp目录中的文件.

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

momo

@Autowired
ServletContext servletContext;

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

这篇关于Spring MVC在没有请求的情况下在WEB-INF下获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆