How to map a Servlet to only the front page / root path of your webapplication

This post is about Java Web Servlets and will hopefully save you some hours of debugging.

Solution

If you’re lucky enough to use Servlets 3.0 you can specify an empty string “” to match only the root path (http://host:port/<context-path>).

In the web.xml it would be:

<servlet-mapping>
  <name>Servlet1</name>
  <url-pattern></url-pattern>
</servlet-mapping>

And in annotations it would unsurprisingly be:

@WebServlet(name = "Servlet1", urlPatterns = "")

Perfect.

Well not quite, if you’re using a Tomcat server you’ll still be faced with an java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping exception when building the project if you’re on version less than 7.0.28 (that’s when they patched it).

Alternative solution

So what do you do if you’re one of the unlucky ones? Try welcome files.

It could look something like this:

<servlet-mapping>
  <servlet-name>Servlet1</servlet-name>
  <url-pattern>/home</url-pattern>
</servlet-mapping>

<welcome-file-list>
  <welcome-file>/home</welcome-file>
</welcome-file-list>

AFAIK welcome paths will match in all directories and subdirectories so beware of that.

More resources

This entry was posted in Java and tagged , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.