Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the variable in the path of a URI

In Spring MVC I have a controller that listens to all requests coming 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.

like image 538
flybywire Avatar asked Oct 08 '09 10:10

flybywire


2 Answers

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";
}
like image 86
labratmatt Avatar answered Oct 03 '22 05:10

labratmatt


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.

like image 42
Dónal Boyle Avatar answered Oct 03 '22 04:10

Dónal Boyle