Search code examples
servletsgetweb.xmlpath-parameter

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


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?


Solution

  • Your best bet is the URL pattern /xyz/*.

    The Servlet API doesn't support to have the URL pattern wildcard * in the middle of the mapping such as /xyz/*/test nor URI templates. It only allows the wildcard * in the end of the mapping like so /prefix/* or in the start of the mapping like so *.suffix.

    You can extract the path information using HttpServletRequest#getPathInfo(). Here's a basic kickoff example how to extract the path information, null and array index out of bounds checks omitted for brevity:

    @WebServlet("/xyz/*")
    public class XyzServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String pathInfo = request.getPathInfo(); // /{value}/test
            String[] pathParts = pathInfo.split("/");
            String value = pathParts[1]; // {value}
            String action = pathParts[2]; // test
            
            if ("test".equals(action)) {
                // ...
            }
        }
    }
    

    If you want to be able to use URI templates nonetheless, and this is actually intended to be a REST endpoint rather than a HTML page, then take a look at Jakarta REST (JAX-RS):

    @Path("/xyz/{value}/test")
    public class XyzResource {
    
        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public String getTest(@PathParam("value") String value) {
            // ...
        }
    }
    

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