Adding the application name to links in a Web application

Steve Neal Development Leave a Comment

Application servers can run a number of applications. A single Tomcat instance, for example, will create a separate web application for each WAR file it finds in its webapps directory.

The applications will be named the same as their WAR files and can be accessed using URLs that start with that name. For example, to access index.jsp in the root directory of a WAR file called myapp.war running on Tomcat on the localhost you will need the following URL:

http://localhost:8080/myapp/index.jsp

When there are multiple applications running in the same Tomcat server, they must all have different names.

Any absolute URLs that you need to include in your application must include the applictions name at the start. For example, if in index.jsp we want to reference an image in ‘/images/banner.png’ the absolute URL will be: ‘/myapp/images/banner.png’.

It is bad practice to hard code the application’s name in the URL as this may change for different deployments of the application. Instead, it may be added dynamically using the following scriptlet:

${pageContext.request.contextPath}

So, to add an img tag that refers to the banner image use:

<img src="${pageContext.request.contextPath}/images/banner.png"/>

Alternatively, there are a number of custom tag libraries that will automatically do this for you. Spring MVC ships with such a tag:

<spring:url value='/images/banner.png'>

this will achieve the same results as the scriptlet shown above but is simpler to remember when adding a number of links in your JSPs.

Leave a Reply

Your email address will not be published. Required fields are marked *