Servlet and path parameters like /xyz/{value}/test, how to map in web.xml?

BlackEagle picture BlackEagle · Jan 3, 2012 · Viewed 46.1k times · Source

Does servlet support urls as follows:

/xyz/{value}/test

where value could be replaced by text or number.

How to map that in the web.xml?

Answer

BalusC picture BalusC · Jan 3, 2012

It's not supported by Servlet API to have the URL pattern wildcard * in middle of the mapping. It only allows the wildcard * in the end of the mapping like so /prefix/* or in the start of the mapping like so *.suffix.

With the standard allowed URL pattern syntax your best bet is to map it on /xyz/* and extract the path information using HttpServletRequest#getPathInfo().

So, given an <url-pattern>/xyz/*</url-pattern>, here's a basic kickoff example how to extract the path information, null checks and array index out of bounds checks omitted:

String pathInfo = request.getPathInfo(); // /{value}/test
String[] pathParts = pathInfo.split("/");
String part1 = pathParts[1]; // {value}
String part2 = pathParts[2]; // test
// ...

If you want more finer grained control like as possible with Apache HTTPD's mod_rewrite, then you could look at Tuckey's URL rewrite filter.