有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

class Venue {
    private String city;
    private String place;

    // Respective getters and setters.
}

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

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

我可以说,在spring中,有没有一种方法可以将路径变量绑定到模型对象(在本例中为地点)而不是获取每个单独的参数


共 (3) 个答案

  1. # 1 楼答案

    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
    }
    

    注意,JavaBean必须具有cityplace属性才能工作

    有关更多信息,您可以查看withParamGroup() example from spring-projects/spring-mvc-showcase

  2. # 2 楼答案

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

    A @PathVariable argument can be of any simple type such as int, long, Date, etc. Spring automatically converts to the appropriate type or throws a TypeMismatchException if it fails to do so.

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

    自定义类将有权访问WebRequest,并将返回一个域对象,其中包含从该请求提取的数据

  3. # 3 楼答案

    您可以提供HandlerMethodArgumentResolver接口的实现。这个接口主要用于以Spring所不能的方式解析控制器方法的参数(这基本上是您正在尝试的)。您可以通过实现以下两种方法来实现这一点:

    public boolean supportsParameter(MethodParameter mp) {
        ...
    }
    
    public Object resolveArgument(mp, mavc, nwr, wdbf) throws Exception {
        ...
    }
    

    您可以通过以下方式将实现注入Spring上下文:

    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="com.path.ImplementationOfHandlerMethodArgumentResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>
    

    当Spring遇到无法解析的参数时,它将调用您的方法supportsParameter(),查看您的解析程序是否可以解析该参数。如果您的方法返回true,那么Spring将调用resolveArgument()方法来实际解析参数。在这个方法中,您可以访问NativeWebRequest对象,您可以使用它获取contextPath之外的路径。(在您的情况下是:/venue/{city}/{place}) 您可以解析请求路径并尝试获取城市/地点字符串 填充到您的场地对象中