1

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/

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

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" />

Thanks for help.

John
  • 1,350
  • 5
  • 27
  • 49
  • 1
    can you try resources/css/style.css in the link tag for the css? – Zeus Dec 26 '13 at 18:41
  • Zeus's solution will not work for some URLs (e.g., `http://localhost:8080/MyApp/some/other/path.html`) as Sotirios explained in his answer, unless you specify proper tag in your . – Alexey Dec 26 '13 at 19:18

2 Answers2

2

When specifying a path like

<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

But if the current URL was

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

then the same path css <link> would be resolved to

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

which is not what you want.

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" />

or with EL as

<link href="${pageContext.request.contextPath}/resources/css/style.css" rel="stylesheet"  type="text/css" />
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

A leading slash in a URL makes it relative to the Host, in your case http://localhost:8080/. So to be relative to the current URL leave it out.

You can also use <c:url > which makes the address relative to the servlet address, no matter what the current URL is.

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

This way, even if you have opened the page http://localhost:8080/MyApp/whatever/, the stylesheet will have the correct URL.

a better oliver
  • 26,330
  • 2
  • 58
  • 66