JSP Relative Links

Published: Sunday, 7 May 2006

Web applications are deployed to a context, so you must be careful not to hard code any links.

e.g. You should be able to deploy the same application to / and also /test of your web container.

Below is a solution to this problem.

HTML Base Href

Generate a base href, e.g.

<base href="http://www.example.com"/>

so that on the client side, all links will be resolved relative this.

You can do this by using strut’s html:base tag, or create the HTML base element yourself. The target can be taken from application context using jstl

${pageContext.request.contextPath}

or Java expression

<%= request.getContextPath() %>

Absolute links

Absolute links must be created for any “a href” attribute or any “img src” attribute.

Because the context can be different, be careful to prefix each link using something dynamic to generate the URLs.

Struts provides html:link and html:img attributes, which will automatically rewrite and encode URLs for you. JSTL can use the ${pageContext.request.contextPath} variable, and you can use the request object directly as in the examples above.