在Spring中将路径变量绑定到自定义模型对象

Sen*_*abu 28 java spring path-variables

我有一个模拟我的请求的类,比如

class Venue {
    private String city;
    private String place;

    // Respective getters and setters.
}
Run Code Online (Sandbox Code Playgroud)

我想支持一个RESTful URL来获取有关场地的信息.所以我有这样的控制器方法.

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

有没有办法,我可以说在春天将我的路径变量绑定到模型对象(在本例中为Venue)而不是获取每个单独的参数?

Lia*_*hou 32

Spring MVC提供了将请求参数和路径变量绑定到JavaBean的能力,在您的情况下是这样Venue.例如:

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

请注意,您的JavaBean必须具有cityplace它的属性才能工作.

有关更多信息,您可以查看spring-projects/spring-mvc-showcase中的withParamGroup()示例


vin*_*tks 3

根据http://static.springsource.org/spring/docs/3.2.3.RELEASE/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates上提供的 Spring 文档,自动仅向简单类型提供支持:

@PathVariable 参数可以是任何简单类型,例如 int、long、Date 等。Spring 会自动转换为适当的类型,如果无法转换,则抛出 TypeMismatchException。

我还没有尝试过@RequestParam和的这种特定组合Model,但看起来您可以通过创建自定义来实现所需的实现WebBindingInitializer,详见http://static.springsource.org/spring/docs/3.2.3.RELEASE/spring -framework-reference/html/mvc.html#mvc-ann-typeconversion

自定义类将有权访问 WebRequest 并返回一个域对象,其中填充了从此请求中提取的数据。