random technical thoughts from the Nominet technical team

Hiding the servlet name in a URL when running Tomcat by using the root context.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...
Posted by jay on Nov 27th, 2005

This is one of those things that seems to be easy enough, but finding out exactly how to do it is not easy. So I thought I would try and document it in a straight forward way.

When you run a web based application that runs in Tomcat then the URL looks something like this

http://www.example.tld/servletname/pageyouwanttovisit

The servlet name is important to Tomcat because it tells it which servlet to send the page request to. In other words, this way you can have many different servlets on the same server and the /servletname/ part tells Tomcat which request goes where. One day we will all switch to IoC containers like Spring and this crude URL-based mechanism will be disappear.

However until then you have the problem that you end up with the servlet name appearing in every URL, which is quite often not relevant to your site and something you would prefer is not there. Especially you have a site that only runs one servlet. For example this blog is delivered via Blojsom but we don’t want that leading to a /blojsom/ appearing in every URL. What we want is something that looks like this:

http://www.example.tld/pageyouwanttovisit

To do this you need to edit the .xml content file for that servlet, which can be found in (Tomcat 5 and above):

$CATALINA_HOME/conf/engine/host/servletname.xml

So if you were looking for this file for the servlet infoglueDeliverLive on a standard Tomcat install, then it would be found as

$CATALINA_HOME/conf/Catalina/localhost/infoglueDeliverLive.xml

Inside that file is the context tag, which tells Tomcat what URL part to link to the servlet. For the same example the opening part of that tag looks like this:

<Context path="/infoglueDeliverLive" docBase="/usr/local/jakarta-tomcat-5.5.7//webapps/infoglueDeliverLive" debug="0" reloadable="true" crossContext="true">

So to get rid of the need for the servlet name in the URL you just set the path attribute to an empty string (the root context). In this example the whole opening part of the tag then looks like this:

<Context path="" docBase="/usr/local/jakarta-tomcat-5.5.7//webapps/infoglueDeliverLive" debug="0" reloadable="true" crossContext="true">

And that is all. To make it even easier, this is hot-deployable - you do not need to restart Tomcat for it to take effect.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Recent Posts

Highest Rated

Categories

Archives

Meta: