John F.
John F.

Reputation: 4840

Java - Managing Context Path

I have been working on an application that is currently being to deployed to numerous environments. However, we are having issues with the context path when deployed to certain environments. This is a Java/Spring application running on Tomcat 6. The deployment process is handled by system administrators so I don't have much visibility into the process so I'm trying to come up with some ways of handling the scenario. With all URLS, we prepend them with request.getContextPath(). Under normal circumstances, this works fine. For example, if WAR has the filename site1.war, it gets deployed to

/site1/

However, we have a couple of other environments where the WAR is deployed and it contains a rootpath outside of the application root so it ends up with

/otherroot/site1/

So the application root path is /site1/ and is unaware of this other rootpath /otherroot/. In this case, calling getContextPath() returns /site1/ when in reality the path that we want is /otherroot/site1/.

Now, one thing that has me confused is that when we use #{request.contextpath} within a JSF page when defining images (images, stylesheets or javascript files), the URL is correct when looking at the source. For example, given the /otherroot/site/ url, if I set

<img src="#{request.contextPath}/image1.png"/>, when I look at the source of the rendered page, I see /otherroot/site1/image1.png. Now, if I set some JS variable to hold the context path every time the page is rendered, I get a different result. For example,

<script>
    APP.ROOT_PATH = '#{request.contextPath}';
</script>

This renders the following:

APP.ROOT_PATH = '/site1'

This is causing some issues because we make use of asynchronous requests so we use the url to properly request data from the client side.

So my question is, what is the best strategy for writing an application that can run under any given path?

Upvotes: 1

Views: 274

Answers (1)

Vineet Kasat
Vineet Kasat

Reputation: 1014

You can achieve this by using interceptors which would identify the environment for you. You can pass the environment path through model to UI which could be used by UI. For eg. /otherroot/site1/ , in this site1 is the context name and otherrrot is the environment.

When yo hit your server to render a jsp, interceptor will analyze this url and come to know that url has something to do with otherroot1. This environemnt and related data can be set in model which could be used to fetch js, images etc and for any other ajax call.

No need to rely on url context path once page is rendered.

Upvotes: 1

Related Questions