在 Spring MVC 中以编程方式设置资源路径 [英] Setting resource paths programatically in spring MVC

查看:47
本文介绍了在 Spring MVC 中以编程方式设置资源路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 MVC 应用程序需要访问 servlet 上下文之外的缩略图和视频文件.所以我已经将 servlet-context.xml 设置为具有以下内容:

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/" />

因此/home/john/temp_jpgs/中的图像可用于/resources 下的任何 jsp.

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?

谢谢,约翰.

推荐答案

如果 <resources ... 标签不符合您的要求,您可以子类化 ResourceHttpRequestHandler 包括任何功能你需要.

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

示例:自定义位置的 ResourceHttpRequestHandler 子类

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;
    }
}

现在,您可以删除 <resources ... 标记并在上下文中注册您的处理程序,如下所示.然后,对 /resources/** 的请求将被路由到您的自定义类.您基本上可以通过设置器更改 yourCustomPath 变量来控制 location.

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>

您现在可以将 resourceHandler bean 注入任何其他类,调用 setter 来设置 yourCustomPath 并以编程方式更改它.

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

这篇关于在 Spring MVC 中以编程方式设置资源路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆