2012-11-28 79 views
1

我正在使用RESTFul URL來開發Spring MVC應用程序。我遇到了靜態資源路徑解析問題。Spring mvc RESTFUL找不到具有URI的HTTP請求的映射

我在JSP頁面的靜態資源寫成:

<link type="text/css" rel="stylesheet" href="resources/css/960_16_col.css"> 

所以當頁面被Tomcat 7呈現的,我得到一個錯誤:

No mapping found for HTTP request with URI [/mycoolapp/instances/demo/resources/css/960_16_col.css]

在我servlet- context.xml中我有:

<annotation-driven /> 
<resources mapping="/resources/**" location="/resources/" /> 

我的web.xml文件是:

<servlet> 
    <servlet-name>appServlet</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
      <init-param> 
       <param-name>contextConfigLocation</param-name> 
       <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> 
      </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
    <servlet-name>appServlet</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping> 

最後我的控制器:

@RequestMapping(value = "/instances/{proj}/{type}", method = RequestMethod.GET) 
public ModelAndView instances(Locale locale, Model model, 
     @PathVariable("proj") String project, 
     @PathVariable("type") String type) { 
    . . . 
} 

沒有寧靜的網址,一切正常工作。 谷歌搜索和堆疊,我找到了解決辦法使用絕對路徑的靜態資源後:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/960_16_col.css"> 

寫在這個stack overflow question,但它似乎是一個解決辦法。

有沒有一種優雅的方式來解決靜態URL和他們的親屬?

+0

'$ {pageContext.request.contextPath}'是一樣簡單,你可以得到它。我不認爲這是一種解決方法。考慮一下,變量/標籤必須能夠適應Web應用程序作爲根web應用程序和具有領先上下文名稱的開發環境運行的時間。所以你需要一些變量來適應你在絕對URL中可能期望的差異。僅供參考,您可以使用相對URL,但通常認爲它是一個壞主意(在SO上搜索優缺點)。 – nickdos

回答

0

進口標記庫

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 

然後使用URL標記:

<c:url var="myCss" value="/resources/css/960_16_col.css"/> 
<link type="text/css" rel="stylesheet" href="${myCss}"/> 

或不創建一個變量:

<link type="text/css" rel="stylesheet" href="<c:url value='/resources/css/960_16_col.css'/>" /> 
+0

這是我第一次嘗試,但它不會工作,因爲它添加了請求路徑。所以問題就改變了,將請求的路徑添加到靜態url。你知道是否有可能指定的URL ctag只添加contextPath url? – 0x41ndrea

+0

這就是你應該這樣做的方式......我想你可能有你的資源在錯誤的位置 – NimChimpsky

相關問題