@RequestParam和@PathVariable封装

时间:2018-01-09 14:57:11

标签: java spring spring-mvc spring-boot request-mapping

有没有办法将这两个值封装到一个对象中?

public ResponseEntity<TestResponse> test(@PathVariable("customerId") String customerId,
        @RequestParam(name = "reason", required = true) String reason,
        @RequestParam(name = "attribute", required = true) List<String> attributes) {

我认为我应该能够这样做:

public ResponseEntity<TestResponse> test(@MaybeSomeMagicAnnotation? Request request) {

其中Request类具有这三个属性(customerId,reason,attributes)。

我使用的是春季靴子1.5.9

1 个答案:

答案 0 :(得分:4)

您应该能够通过定义与请求参数匹配的对象等来实现此目的。

示例(未经测试):

public class MyRequest {
   @NotNull
   private String customerId;

   @NotNull
   private String reason;

   @NotNull
   @NotEmpty
   private List<String> attributes;

   // getters and setters left out for brevity.
}

然后在你的控制器中:

public ResponseEntity<TestResponse> test(@Valid MyRequest request) {
    ...
}