Handling links on the Server Side

If we create a web application and then deploy it to context “/webapp” all resources will be relative to this context, for example:

http://localhost:8080/webapp/css/styles.css

How do we handle this on the sever side ? If we have main.jsp and we want to link to styles.css

<a href="???/css/styles.css">click here</a>

If we hardcode href="webapp/css/styles.css" then all links will break if we ever deploy to a different context path.

One solution is to dynamically retrieve the context using:

${pageContext.request.contextPath}

this would return “/webapp“.

We would then have to append this to every link:

href="${pageContext.request.contextPath}/css/styles.css"

We can improve this by using the JSTL core tags:

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

So now our links are shortened to :

href="${root}/css/styles.css"

—————-

Another approach is to use the HTML <base> tag.

<base href="${pageContext.request.contextPath}/">

all relative links (those not starting with “/”, now become relative to the context path.

<a href="css/styles.css">click here</a>

Note: When using tag it should be closed (<base .../>) to prevent issues with IE6.

—————-

Another approach is to use the JSTL url tag or the Spring url tag.

<a href="<c:url value="/css/styles.css"/>" >click here</a>
<a href="<spring:url value="/css/styles.css"/>" >click here</a>
Advertisements
Posted in HTML, Java, Web

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: