如何正确使用Spring MVC中的外部文件?

时间:2016-11-25 10:44:23

标签: java spring file spring-mvc

我无法访问未存储在src/main/项目路径

中的文件

项目结构:
Project tree

现在我可以访问webapp/resources中的所有文件,但无法访问userResources文件夹中的文件

Spring resourceHandler:

@EnableWebMvc
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
 //some configs

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/resource/**").addResourceLocations("/resources/");
       registry.addResourceHandler("/vendors/**").addResourceLocations("/vendors/");
       //this line won't work
       registry.addResourceHandler("/userResources/**").addResourceLocations(
        "home/pika/workspace/Spring/Bookmarks/userResources")
       );
   }
}

在视图中

<img class="fb-image-lg" src="/home/pika/workspace/Spring/Bookmarks/userResources/admin/profile/wallImage.png" alt="Profile wall image" align="left">

找不到图片,我尝试更改src:“/ userResources/admin/profile/wallImage.png”无论如何它都不起作用

<img class="fb-image-profile thumbnail" src="/resources/images/defaultProfilePhoto.png" alt="Profile face image" align="left">

找到图片。

我做错了什么?

PS Github repo可能有助于您了解项目结构

1 个答案:

答案 0 :(得分:2)

在Web应用程序内部查找资源位置"home/pika/workspace/Spring/Bookmarks/userResources",而不是在文件系统上查找(就像以“/ resources”开头的另一个)。要定位文件系统,请使用文件URL:

file:/home/pika/workspace/Spring/Bookmarks/userResources

然而,这是一个可怕的想法:您将部署该应用程序的Web服务器与您在开发人员计算机上的目录结构不同。您应该在webapp中包含这些资源。或者将这些图像存储在数据库中。或者在文件系统上,但至少使用基于外化的目录,在代码中没有这样的硬编码。