Spring:在上下文根之外提供静态资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5456635/
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
Spring : serving static resources outside context root
提问by Homer
in a web app, I need to serve static contents (images) located outside the application context directory. The overall application architecture requires me to use Tomcat to perform this. I thought I could benefit from Spring's <mvc:resources>to configure a mapping between application URLs and directory contents. But AFAIK it's mappingattribute only handles context relative, or classpath mappings. Hence, what I'd like to use :
在 Web 应用程序中,我需要提供位于应用程序上下文目录之外的静态内容(图像)。整个应用程序架构需要我使用Tomcat来执行此操作。我认为我可以从 Spring 的<mvc:resources>配置应用程序 URL 和目录内容之间的映射中受益。但是 AFAIK 它的mapping属性仅处理上下文相关或类路径映射。因此,我想使用的是:
<mvc:resources location="/images/**" mapping="/absolute/path/to/image/dir"/>
doesn't work. As I'd rather avoid writing a simple file transfer servlet, I'd be glad if anyone could give me some pointers on existing Spring based solutions/workarounds.
不起作用。因为我宁愿避免编写一个简单的文件传输 servlet,如果有人能给我一些关于现有基于 Spring 的解决方案/解决方法的指示,我会很高兴。
Many thanks.
非常感谢。
Homer
荷马
回答by axtavt
<mvc:resources>can serve resources from the outside, you need to use the usual Spring resource path syntax:
<mvc:resources>可以从外部提供资源,您需要使用通常的Spring 资源路径语法:
<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir/"/>
回答by Jebil
There is one more simple correction
还有一个更简单的修正
the code should be
代码应该是
<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir/"/>
<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir/"/>
Did you notice the difference ? You need to put '/' at the end of the absolute path.
你注意到区别了吗?您需要将“/”放在绝对路径的末尾。
or you can use the java configuration
或者你可以使用java配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String rootPath = System.getProperty("user.home");
String imagePath = "file:"+rootPath + File.separator + "tmpFiles/";
System.out.println(imagePath);
registry.addResourceHandler("/resources/**").addResourceLocations("resources/");
registry.addResourceHandler("/tmpFiles/**").addResourceLocations(imagePath);
}
Its working for me.
它对我来说有效。

