2013-01-17 243 views
2

我的MVC應用程序需要訪問縮略圖和視頻文件的servlet上下文之外。所以我已經設置了該servlet-context.xml中有以下幾點:設置資源路徑MVC

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

所以圖像內的/ home /是約翰/ temp_jpgs /可用下/資源的任何JSP。

然而,這僅用於測試,我希望能夠以編程方式設置此位置。我怎麼做?

感謝, 約翰。

回答

4

如果<resources ...標記不符合您的要求,您可以繼承ResourceHttpRequestHandler以包含所需的任何功能。

例:子類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

<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豆到任何其他類,調用setter設置yourCustomPath和編程方式改變它。

+0

謝謝kevinpeterson。我是Spring的新手,所以我需要一些幫助來設置這個解決方案。我將如何添加一個新的路徑,並使用這個新的類? – user1988235

+0

查看更新的答案 - 我已經添加了一個更具體的例子。如果不清楚,請告訴我。 – kevinpeterson

+0

非常感謝您的時間和精力。正是我需要的。 – user1988235