11

Is it possible to map URLs to servlets (maybe something specific with Tomcat) so that the two following URLs (with {id}'s being variables retrievable from code),

/users/{id}/a

/users/{id}/b

map to two different servlets, or will I have to implement some sort of filter of my own for a servlet mapped to /users/*?

To be more clear, any URL with the pattern /users/*/a should map to the same servlet. The same goes for /users/*/b.

irwinb
  • 993
  • 2
  • 10
  • 20

3 Answers3

8

You could map it on /users/* and extract information from HttpServletRequest#getPathInfo():

@WebServlet("/users/*")
public class UsersController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] pathInfo = request.getPathInfo().split("/");
        String id = pathInfo[1]; // {id}
        String command = pathInfo[2]; // a or b
        // ...
    }

}

(obvious validation on array size omitted)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
6

This looks like it might be a good candidate for JAX-RS. I'm not sure what business logic your servlets currently perform, but this option addresses your servlet mapping question and may be appropriate.

@Path("/users/{id}")
public class User { 

    @Path("a")
    public String doA(@PathParam("id") final int id) { ... }

    @Path("b")
    public String doB(@PathParam("id") final int id) { ... }

}
shelley
  • 7,206
  • 4
  • 36
  • 63
1

I don't think it's possible. Either use the UrlRewriteFilter or some framework like Spring-MVC that is capable of mapping more complex URLs

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140