Bind Path variables to a custom model object in spring

Senthil Babu picture Senthil Babu · Jun 17, 2013 · Viewed 32.3k times · Source

I have a class that models my request, something like

class Venue {
    private String city;
    private String place;

    // Respective getters and setters.
}

And I want to support a RESTful URL to get information about a venue. So I have controller method like this.

@RequestMapping(value = "/venue/{city}/{place}", method = "GET")
public String getVenueDetails(@PathVariable("city") String city, @PathVariable("place") String place, Model model) {
    // code
}

Is there a way, I can say in spring to bind my path variables to the model object (in this case Venue) instead of getting every individual parameter?

Answer

Liang Zhou picture Liang Zhou · Apr 24, 2014

Spring MVC offers the ability to bind request params and path variables into a JavaBean, which in your case is Venue. For example:

@RequestMapping(value = "/venue/{city}/{place}", method = "GET")
public String getVenueDetails(Venue venue, Model model) {
    // venue object will be automatically populated with city and place
}

Note that your JavaBean has to have city and place properties for it to work.

For more information, you can take a look at the withParamGroup() example from spring-projects/spring-mvc-showcase