Spring访问静态资源

时间:2013-12-26 18:36:43

标签: css spring-mvc

我遇到了在spring mvc中加载静态文件的问题。我在我的java配置中有这样的东西:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

部署我的应用并在浏览器中访问时

http://localhost:8080/MyApp/

没有加载CSS。当我找到源代码时,我发现这条道路是这样的:

http://localhost:8080/resources/css/style.css

哪个不对。如果我将其更改为:

http://localhost:8080/MyApp/resources/css/style.css

然后我可以看到我的css文件。我究竟做错了什么? 在我的CSS中,我链接到这样的资源:

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

指定类似

的路径时
<link href="/resources/css/style.css" rel="stylesheet"  type="text/css" />

如果路径以/为前缀,浏览器会将该路径附加到您的主机,而不是您的应用程序上下文。例如,假设您第一次提出要求

http://localhost:8080/MyApp/

然后你的浏览器会尝试获取

的css
http://localhost:8080/resources/css/style.css
你已经注意到了。如果您没有在路径的前面放置/,如

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

然后浏览器将使用当前位置URL作为基础。

http://localhost:8080/MyApp/resources/css/style.css

但是如果当前的网址是

http://localhost:8080/MyApp/some/other/path

然后将相同的路径css <link>解析为

http://localhost:8080/MyApp/some/other/path/resources/css/style.css

这不是你想要的。

您希望css链接始终在应用程序的上下文路径上解析。你可以使用JSTL core taglib这样做

<link href="<c:url value="/resources/css/style.css" />" rel="stylesheet"  type="text/css" />

或EL为

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

答案 1 :(得分:0)

在您的案例http://localhost:8080/中,网址中的前导斜杠使其与主机相关。因此,相对于当前的URL,请将其删除。

您也可以使用<c:url >使地址相对于servlet地址,无论当前的URL是什么。

<link href="<c:url value="/resources/css/style.css"/>" rel="stylesheet"  type="text/css" />

这样,即使您打开了页面http://localhost:8080/MyApp/whatever/,样式表也会有正确的网址。

相关问题