views:

1174

answers:

3

In spring mvc I have a controller that listens to all requests comming to /my/app/path/controller/*.

Let's say a request comes to /my/app/path/controller/blah/blah/blah/1/2/3

How do I get the /blah/blah/blah/1/2/3 part, i.e. the part that matches the * in the handler mapping definition.

In other words I am looking for something similar that pathInfo does for servlets but for controllers.

+3  A: 

In Spring 3 you can use the @ PathVariable annotation to grab parts of the URL.

Here's a quick example from http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

@RequestMapping(value="/hotels/{hotel}/bookings/{booking}", method=RequestMethod.GET)
public String getBooking(@PathVariable("hotel") long hotelId, @PathVariable("booking") long bookingId, Model model) {
    Hotel hotel = hotelService.getHotel(hotelId);
    Booking booking = hotel.getBooking(bookingId);
    model.addAttribute("booking", booking);
    return "booking";
}
labratmatt
I have been trying to figure out how to do this! Unfortunately I'm stuck with Spring 2.5 for now.
Donal Boyle
Excellent, first search on Google, first result, first answer in stackoverflow question :)
seanhodges
+1  A: 

In Spring 2.5 you can override any method that takes an instance of HttpServletRequest as an argument.

org.springframework.web.servlet.mvc.AbstractController.handleRequest

In Spring 3 you can add a HttpServletRequest argument to your controller method and spring will automatically bind the request to it. e.g.

    @RequestMapping(method = RequestMethod.GET)
    public ModelMap doSomething( HttpServletRequest request) { ... }

In either case, this object is the same request object you work with in a servlet, including the getPathInfo method.

Donal Boyle
A: 

Thse guys have quite a nice way of implementing this. http://www.carbonfive.com/community/archives/2007/06/parameterized_rest_urls_with_spring_mvc.html

Not with annotations but it is quite nice.

Pablojim