Resolved: Mulptiple dynamic values in url mapping in servlet

In this post, we will see how to resolve 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?

Best Answer:

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 :
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:

If you have better answer, please add a comment about this, thank you!