如何将@RequestParam 映射到对象?

How to map @RequestParam to object?

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String content(
      @RequestParam int a,
      @RequestParam String b,
      ...
      @RequestParam String n;
) {

}

我能以某种方式直接将所有 @RequestParam 映射到一个 java 对象吗?

public class RestDTO {
   private int a;
   private String b;
   private String n;
}

在我看来你有事可做。 内容方法将是这样的:

public String content(@RequestParam RestDTO restDTO){...}

rest DTO 应该有正确的设置器。 当你这样做时发生了什么?

方法:1 您需要将方法更改为 POST 并且可以接收 DTO 对象作为控制器方法的参数,如下所示。使用 GET 方法你无法实现它,因为 GET 没有正文。

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public String content( @RequestBody RestDto restDto) {
 ....
}

方法:2 或者,如果您仍想使用 GET 方法,则向 RestDto 添加一个构造函数,如下所示

public RestDto {
    public RestDto(int a, String b, String n){
     this.a = a;
     this.b = b;
     this.n = n;
   }
}

并且您在控制器中调用构造函数如下:

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String content(
    @RequestParam int a,
    @RequestParam String b,
     ...
    @RequestParam String n;
) {
   RestDto restDto = new RestDto(a,b,n);
}

如果遇到:

no matching editors or conversion strategy found

可能是因为您在控制器方法中不必要地包含了 @RequestParam

确保作为请求参数接收的属性在目标对象上具有 getter 和 setter(在本例中请求参数 abn ):

public class RestDTO {

    private int a;
    private String b;
    private String n;

    public int getA() {return a;}
    public void setA(int a) {this.a = a;}

    public int getB() {return b;}
    public void setB(int b) {this.b = b;}

    public int getC() {return c;}
    public void setC(int c) {this.c = c;}

}

在控制器方法中添加目标对象作为参数,但使用@RequestParam注释。每个匹配的请求参数都会调用目标对象的setter方法。

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String content(RestDTO restDto) {

}