Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring : serving static resources outside context root

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

like image 614
Homer Avatar asked Mar 28 '11 08:03

Homer


People also ask

Which bean serve static resources in spring?

Using Spring Boot Spring Boot comes with a pre-configured implementation of ResourceHttpRequestHandler to facilitate serving static resources. By default, this handler serves static content from any of the /static, /public, /resources, and /META-INF/resources directories that are on the classpath.

How do you serve a static html content page in spring boot?

Just put index. html in src/main/resources/static/ folder and static html is done!

Where do static resources go in spring boot?

Spring Boot will automatically add static web resources located within any of the following directories: /META-INF/resources/ /resources/ /static/

How does Spring MVC handle static content?

Create a static file final. Update the Spring configuration file HelloWeb-servlet. xml under the WebContent/WEB-INF folder as shown below. The final step is to create the content of the source and configuration files and export the application, which is explained below.


2 Answers

<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/"/> 
like image 66
axtavt Avatar answered Oct 22 '22 06:10

axtavt


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.

like image 21
Jebil Avatar answered Oct 22 '22 08:10

Jebil