Spring访问静态资源 [英] Spring access to static resources
问题描述
我有问题在加载静态文件在春季mvc。我在我的java配置像这样:
I am having issue with loading static files in spring mvc. I have in my java config something like this:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
部署我的应用程序并在浏览器中访问
When I deploy my app and visit it in browser
http://localhost:8080/MyApp/
未加载CSS。当我去源我看到路径是这样的:
No CSS is loaded. When I go to source I see that path is something like this:
http://localhost:8080/resources/css/style.css
这不正确。如果我将其更改为:
Which is incorrect. If I change it to:
http://localhost:8080/MyApp/resources/css/style.css
然后我可以看到我的css文件。我究竟做错了什么?
在我的CSS我链接到这样的资源:
Then I can see my css file. What am I doing wrong? In my css I am linking to resources like this:
<link href="/resources/css/style.css" rel="stylesheet" type="text/css" />
感谢您的帮助。
推荐答案
指定类似
<link href="/resources/css/style.css" rel="stylesheet" type="text/css" />
其中路径以 /
浏览器会将该路径附加到您的主机,而不是您的应用程序上下文。例如,假设您第一次请求
where the path is prefixed with /
, the browser appends that path to the your host, not to your application context. For example, say you made your first request to
http://localhost:8080/MyApp/
那么您的浏览器将尝试在
then your browser would try to get the css at
http://localhost:8080/resources/css/style.css
你已经注意到了。如果你不把 /
放在路径前面,例如
as you've noticed. If you don't put a /
at the front of the path like
<link href="resources/css/style.css" rel="stylesheet" type="text/css" />
那么浏览器将使用当前位置网址作为基础。
then the browser will use the current location URL as the base.
http://localhost:8080/MyApp/resources/css/style.css
但是如果当前URL是
http://localhost:8080/MyApp/some/other/path
然后使用相同的路径css < link> ;
将解析为
then the same path css <link>
would be resolved to
http://localhost:8080/MyApp/some/other/path/resources/css/style.css
这不是你想要的。
您希望css链接始终在应用程序的上下文路径上解析。您可以使用JSTL core
taglib这样做
You want to css link to always be resolved on your application's context path. You can do this with the JSTL core
taglib like so
<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" />
这篇关于Spring访问静态资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!