【问题标题】:Spring mvc RESTFUL no mapping found for HTTP request with URISpring mvc RESTFUL 找不到带有 URI 的 HTTP 请求的映射
【发布时间】:2012-11-28 11:23:09
【问题描述】:

我正在开发一个带有 RESTFul url 的 Spring MVC 应用程序。我遇到了静态资源路径解析问题。

我在一个jsp页面中有一个静态资源写成:

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

所以当页面被tomcat 7渲染时,我得到一个错误:

找不到带有 URI [/mycoolapp/instances/demo/resources/css/960_16_col.css] 的 HTTP 请求的映射

在我的 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 并使它们保持相对关系?

【问题讨论】:

  • ${pageContext.request.contextPath} 非常简单。我不认为这是一种解决方法。想一想,该变量/标签必须能够适应 webapp 作为根 webapp 和具有前导上下文名称的开发环境运行时的情况。因此,您需要一些变量来适应您可能在绝对 URL 中所期望的差异。仅供参考,您可以使用相对 URL,但通常认为这是一个坏主意(在 SO 上搜索优缺点)。

标签: java spring-mvc restful-url


【解决方案1】:

尝试使用&lt;spring:url /&gt; 标记,默认情况下会将上下文根附加到 url。

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<link type="text/css" rel="stylesheet" href='<spring:url value="/resources/css/960_16_col.css" htmlEscape="true"/>'/>

http://static.springsource.org/spring/docs/current/spring-framework-reference/html/spring.tld.html

【讨论】:

【解决方案2】:

导入标签库

<%@ 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'/>" />

【讨论】:

  • 这是我的第一次尝试,但它不会工作,因为它添加了请求路径。于是问题变了,把请求的路径加到静态url中。你知道是否可以指定 url ctag 只添加 contextPath url?
  • 这就是你应该这样做的方式......我认为你的资源可能在错误的位置
猜你喜欢
  • 1970-01-01
  • 2013-09-16
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2012-10-26
  • 2011-11-04
  • 1970-01-01
相关资源
最近更新 更多