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?
Asked
Active
Viewed 7,692 times
7

slashnick
- 26,167
- 10
- 55
- 67
-
1Does http://stackoverflow.com/questions/1175587/absolute-url-in-jsp help? – Simon Groenewolt Jun 28 '10 at 08:53
-
No despite the name that shows how to create a url relative to the context root, which does not include the domain. – slashnick Jun 28 '10 at 08:59
-
Ah - too bad, I didn't realize that. You can use request.getServerName() to get the servername - so if you know the protocol you should be fine with the combination of that and the linked question. – Simon Groenewolt Jun 28 '10 at 13:28
-
And use getServerPort() to get the port. – Simon Groenewolt Jun 28 '10 at 13:34
1 Answers
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:
- Is it recommended to use the HTML
<base>
tag? (sensitive subject actually)
-
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