2012-06-26 45 views
20

我想下/WEB-INF/.../Spring MVC的获取在WEB-INF文件,而无需请求

以外的请求得到一个文件(或目录)的保持。我需要它在服务器启动时加载的bean中。

我可以找到的所有解决方案都希望使用ClassPathXmlApplicationContext的XML文件或请求获取servlet上下文或使用当前正在执行的类。似乎丑陋的我。

我怎样才能得到File("/WEB-INF/myDir/")。必须有一种方式,不!!

回答

35

只要你的bean是在Web应用程序上下文,你能够获得的ServletContext实例声明(使用ServletContextAware,或通过自动装配)。

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

编辑由MOMO:

@Autowired 
ServletContext servletContext; 

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

+1 for'servletContext.getRealPath(“/ WEB-INF/myDIR /”)' – bizzr3

+0

@mahesh提供的解决方案稍好一些,因为服务图层不应该具有Web层的依赖关系。ServletContext只应该在控制器中执行。 – Dani

+0

另外,getRealPath方法可能会返回null,具体取决于已部署哪个应用程序服务器和/或应用程序,例如weblogic中的.war。 –

2

如果文件位于WEB_INF\classes目录中,则可以使用类路径资源。这也正是在src/main/resources目录中的所有文件都将被复制到使用正常的Maven构建...

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

'/ WEB-INF/myDir /'不是类路径资源。 – axtavt

+0

@axtavt哦是的,假设它是WEB-INF/classes – NimChimpsky

7

我用春天DefaultResourceLoader资源到一个* .jar文件WEB-INF或任何资源读取里面。像魅力一样工作。祝你好运!

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()); 
} 
+0

'DefaultResourceLoader'不能读取WEB-INF内部,您需要'ServletContextResource'来获得这个 – Derp

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

“文件”文件夹中应该是“主/资源”文件夹中的孩子

1

这是你如何能做到这一点,如果你只是想从一个服务(而不是通过ServletContext中)访问:

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

注意,最后一行可能会引发IOException,所以你需要捕捉/重投

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

+1

谢谢,但问题是关于在WEB-INF下使用它 – momomo

0

不完全关系到你的问题,但... 下面是一些通用sulution我用Spring这样做,您就能在Web应用程序中加载性能(支持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(); 
} 

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

相关问题