user1988235
user1988235

Reputation: 69

Setting resource paths programatically in spring MVC

My MVC application will need access to thumbnails and video files outside the servlet context. So I have set up the servlet-context.xml to have the following:

<resources mapping="/resources/**" location="/resources/,file:/home/john/temp_jpgs/" />

So the images inside /home/john/temp_jpgs/ are available to any jsp under /resources.

However, this is only for testing, and I would like to be able to set this location programatically. How do I do that?

Thanks, John.

Upvotes: 2

Views: 4868

Answers (1)

kevinpeterson
kevinpeterson

Reputation: 1172

If the <resources ... tag doesn't do what you want, you could subclass ResourceHttpRequestHandler to include whatever functionality you need.

Example: Subclass ResourceHttpRequestHandler for custom Location

package com.test;

public class MyCustomResourceHttpRequestHandler extends ResourceHttpRequestHandler {

    private String yourCustomPath;

    @Override
    protected Resource getResource(HttpServletRequest request) {
    String path = (String)  request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...

       //put whatever logic you need in here
       return new FileSystemResource(yourCustomPath + path);

    }

    public void setYourCustomPath(String path){
        this.yourCustomPath = path;
    }
}

Now, you can drop your <resources ... tag and register your handlers in the context as below. Then, requests coming in for /resources/** would get routed to your custom class. You would basically be controlling the location by changing the yourCustomPath variable via setters.

<bean name="resourceHandler" class="com.test.MyCustomResourceHttpRequestHandler">
    <property name="locations">
        <list>
            <!-- you'll be overriding this programmatically -->
            <value>/resources/</value>
        </list>
    </property>
</bean>

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>
            <entry key="/resources/**" value-ref="resourceHandler"/>
        </map>
    </property>
</bean>

You can now inject the resourceHandler bean into any other class, call a setter to set yourCustomPath and change it programmatically.

Upvotes: 4

Related Questions