5

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?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Barun
  • 503
  • 5
  • 13
  • 22

3 Answers3

11

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

Russ
  • 1,471
  • 1
  • 11
  • 5
7

Is this what you're looking for?

${pageContext.servletContext.contextPath}

and then in your jsp:

<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/css/page.css"   media="all"    type="text/css" />
Brane
  • 3,257
  • 2
  • 42
  • 53
vector
  • 7,334
  • 8
  • 52
  • 80
0

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