While including css, js and images in my jsps I am facing a problem resolving relative urls. The urls get changed on refreshing the page or clicking the back button. I suppose one solution to the problem would be to include external files by using absolute urls. But I can't find out how to use a reference to the relative url and use it. Can anyone please help me on this?
3 Answers
This would also work and may be easier to read and has some extra benefits such as proper escaping and optional inclusion of parameters
<link href="<c:url value="/style/style.css"/>" rel="stylesheet" type="text/css" />

- 1,471
- 1
- 11
- 5
Answered this old question because absolute URLs can be useful for javascript using a reverse proxy. The same could work for href too. However in our case the reverse proxy takes care of href urls and so a relative path works just fine.
To get an absolute url for the original question try this:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<link rel="stylesheet" href="${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, pageContext.servletContext.contextPath)}/style/style.css" rel="stylesheet" type="text/css" />
The replace function takes the requestURL i.e.: http:/mydomain.com/context-path/index.html
And replaces the requestURI: /context-path/index.html
With just the context path: /context-path
Resulting in: http:/mydomain.com/context-path
Then append the desired resource: /style/style.css

- 1
- 2