irwinb
irwinb

Reputation: 1013

Servlet Mappings with Variables(Tomcat 7.0)

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.

Upvotes: 11

Views: 4727

Answers (3)

shelley
shelley

Reputation: 7324

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) { ... }

}

Upvotes: 6

BalusC
BalusC

Reputation: 1108722

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)

Upvotes: 8

Bozho
Bozho

Reputation: 597106

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

Upvotes: 1

Related Questions