26

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 mapping attribute only handles context relative, or classpath mappings. Hence, what I'd like to use :

<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.

Many thanks.

Homer

Homer
  • 261
  • 1
  • 3
  • 3

2 Answers2

34

<mvc:resources> can serve resources from the outside, you need to use the usual Spring resource path syntax:

<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir/"/> 
Jon Freedman
  • 9,469
  • 4
  • 39
  • 58
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • 1
    Then I must have misunderstood something. Indeed I tried using the `file:` prefix. And, when tracing a request to a static resource, I noticed in the logs that Spring prepended a slash, resulting in the following mapping : `/file:/absolute/path/to/image/dir`. Needless to say, this tries to map to someting in the context root, which doesn't exist. I'm afraid I can't make use of your suggestion. – Homer Mar 28 '11 at 09:14
  • 3
    Hmm. Should've re-read the example before posting :(. I mixed-up the `mapping` and `location` attributes. Shame on me. Thanks for your reply axtavt. It pointed out where I was wrong, and made me fix my mistake. Things work as expected now. – Homer Mar 28 '11 at 09:33
  • 3
    Guys, thanks so much for this post. It solved an issue for me on a hectic day. I have Spring mixed in with legacy code on an old copy of WebLogic. This tag in my *-servlet.xml helped me find the "images" directory, the new one inside of my *.war and the old "images" directory, I still have to use for the time being, on my computer and the server: `` – Steve Mar 15 '12 at 19:08
  • What should I do since I am using Spring boot and the xml file is absent? – ZhaoGang Nov 02 '18 at 07:11
3

There is one more simple correction

the code should be

<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

@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.

Jebil
  • 1,144
  • 13
  • 25