tags:

views:

38

answers:

3

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?

A: 

Yes, use plain html:

<a href="http://mysite.com"&gt;click&lt;/a&gt;

If you want to use the current site's url, just use request.getServerName(), or in jstl - ${request.serverName}

Bozho
I don't want to hard code the domain as the jsp is used on many sites.
slashnick
you could've included that detail in the question ;)
Bozho
Note: the `ServletRequest#getServerName()` only returns the hostname or IP. Not protocol/port.
BalusC
+1  A: 

Does http://stackoverflow.com/questions/1175587/absolute-url-in-jsp help?

Simon Groenewolt
No despite the name that shows how to create a url relative to the context root, which does not include the domain.
slashnick
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
And use getServerPort() to get the port.
Simon Groenewolt
A: 

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:

BalusC