Search code examples
javawebtomcatservletsurl-mapping

Mulptiple dynamic values in url mapping in servlet


I'm trying to create servlet URL mapping for the dynamic paths. In servlet, we can do dynamic URL mapping with one varying path at the end. I mean, if we wanted to do user/{id} we can do this thing with @WebServlet("/users/*") and then do some string operation to get the id.

What if we want to make this more dynamic, like this /user/{id}/posts/{id}/comments? I've searched for this thing and ended up using Filters to intercept those requests and manually do some operations on the path string to identify the different path keys and values. Is this the only way available, or is there anything else to handle?


Solution

  • Servlet API doesn't support URL pattern wildcard * in middle of the mapping. It only allows the wildcard * at the end of the mapping like so /users/* or in the start of the mapping like so *.suffix.

    In servlet specification, we have no notion of path variables.

    For a servlet point of view, an URL is :

    scheme://host.domain/context_path/servlet_path/path_info?parameters

    where any of the parts (starting from context path may be null)

    So, given an <url-pattern>/user/*</url-pattern>, you can 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
    // ...