3

I'm developing a web-application with tomcat. In the dev env, the application's root address is localhost:8080/myapp/. In production, the root address is www.myapp.com/.

When I use a relative link in my website, e.g. /home, it works fine in production, but the address that I arrive at in my dev is localhost:8080/home, which strips the application's root. Obviously, I cannot just use home, as it would work the first time, but would just concatenate to the end of the address string. I also cannot use the hosts file, and I have no idea how to create an alias or just redirect traffic from some alias to localhost:8080/myapp/.

This seems like a very common issue. Thanks in advance!

1 Answer 1

5

The solution is actually in the code of your web pages and not in any configuration that you can do. Presuming that you are using JSP to generate your HTML, you need to change links like this:

<a href="/home">a link to the root of my webapp</a>

To look like this:

<a href="<%= response.encodeURL(request.getContextPath() + "/home") %>">
  a link to the root of my webapp
</a>

The request.getContextPath is the real magic here: it always returns the prefix that belongs to your webapp, no matter what it is. For the ROOT webapp, it will return "" (empty string). For another it might return "/foo/bar" (if your webapp were deployed as foo#bar.war).

The response.encodeURL will add the session identifier to your URL if the client is not using cookies so that sessions will work when cookies are not available.

If you are using some other content-generation framework (Velocity, Freemarker, etc.) there are analogous ways of achieving the same thing provided by those frameworks.

8
  • Thanks, @Christopher. It's a good enough solution, although I don't want to needlessly increase server load when the path resolution could be delegated to the client.
    – vivri
    May 25, 2012 at 17:35
  • @vivri This is the price you have to pay when writing re-locatable webapps. The increased server load is negligible compared to the other things you are likely to be doing. May 25, 2012 at 17:40
  • This might be true, but for my purposes (a real-time, multi-user service) I need every scrap of CPU I can get.. so I guess it's back to absolute paths and global replace before deployment.. :-/
    – vivri
    May 25, 2012 at 17:42
  • 1
    Everybody runs real-time multi-user services, and everybody does this. Feel free to use search-and-replace. May 25, 2012 at 19:49
  • I think it's actually possible to use an alias in your browser - you just have to use a replace module on httpd. I'll post a how-to when I get to it. That way, you can save time and CPU by using relative links.
    – vivri
    May 25, 2012 at 20:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .