7

If a have <c:url value="/article"/> in a jsp, I actually want it to produce http://mysite.com/context/article. Is there any simple way to acheive this?

slashnick
  • 26,167
  • 10
  • 55
  • 67

1 Answers1

13

There's no simple way. Either hardcode it or output the following:

${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, '')}${pageContext.request.contextPath}

Cumbersome, but there's no shorter/nicer way when you want to take the protocol and port parts of the URL correctly into account. You can at highest assign ${pageContext.request} to ${r}.

<c:set var="r" value="${pageContext.request}" />

so that you can end up with this

${fn:replace(r.requestURL, r.requestURI, '')}${r.contextPath}

That said, I only fail to see how this requirement is useful/valuable. I always code my webapp-specific links to be relative to the current context or to the HTML <base> tag. Otherwise you'll have to a lot of maintenance when your domain, port and/or even the context changes. Why this requirement?

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Programming for an application may not be the requirement for needing an absolute URL. Consider a page that may need to provide a permalink to any given page within that site, knowing the base URL could be beneficial. As an aside I see the EWiki software Confluence needs this to be hard coded in it's configuration section for the base URL instead of trying to figure it out. – Brett Ryan Feb 21 '12 at 04:32
  • how are you referring to static elements such as images, stylesheets, etc.? how do you get to the relative top level? –  Jun 06 '13 at 01:42