Url patterns in Java servlets

by Daniel Winterstein published 05 September 2009

This technical mini-tutorial covers how to set url-patterns in a J2EE config. This lets you pass variables in your path, which can produce more meaningful URLs.

The url-pattern element is a vital part of your web.xml file. It's also a tricky one. The pattern begins from your web-app context. So /myservlet will match http://myserver.com/mywebapp/myservlet

The example pattern above, /myservlet, is exact. It will not match /myservlet/foobar. It will match /myservlet?a=b though (i.e. variables passed by GET are OK).

If you want flexible matching you use *, but the usage is a little strange:

  • /myservlet* will perform an exact match (why? what were they smoking when they decided that?)
  • /myservlet/* is what you want. This will match /myservlet, /myservlet/, /myservlet/foobar, etc.
  • You can also match by filetype using patterns such as *.html
  • All other uses of * will will not work - they are interpreted as the character * itself.

It's a unique pattern globbing system, providing neither power nor flexibility. Still it does the job.

There are more details on url-pattern here: http://www2.roguewave.com/support/docs/leif/leif/html/servletug/7-3.html. An alternative approach to producing elegant meaningful urls is to use apache's rewrite system.