转载

在spring-bootrestapi中传递和验证RequestParam

@RequestParam将方法参数绑定到Web请求参数,语法:

@RequestParam <数据类型> <变量名称>;

代码案例:

@RestController
@RequestMapping("/api")
@Validated
public class HelloWorldController {

   
   @GetMapping("/hello")
   public ResponseEntity<?> sayHello(
         @RequestParam @Size(min= 1, max = 5, message =
 "firstname length must be between 1 and 5") String firstname,
         @RequestParam String middlename,
         @RequestParam(required = false) String lastname){
      /* check lastname value */
      lastname = lastname != null ? lastname : "{lastname-is-optional}";
      return ResponseEntity.ok("Hello " + firstname + " " + middlename + " " + lastname);
   }
}
  • @Validated  - 对控制器的每个方法执行验证(如果有)。
  • @RequestParam  - 在变量中接受Web请求参数。( 注意 :所有使用 @RequestParam 注释的变量接受的请求参数都是强制对应的,除非该参数设置 required = false  @RequestParam(required = false)
  • javax.validation.constraints@Size 用于验证请求参数的长度,不符合条件将抛出   ConstraintViolationException
  • @RequestParam String middlename,:接受变量 middlename中的 强制对应 参数。如果请求中不存在参数,则spring将抛出   MissingServletRequestParameterException
  •  @RequestParam(required = false) String lastname):接受变量 lastname中的 可选 参数。

如果结合Swagger的API注释,你的代码如下:

@ApiOperation(value = "")
@RequestMapping(method = GET, value = "/customcollection/{id}/data")
public Iterable<CustomeType> getData(@ApiParam(value = "The identifier of the time series.")
                            @PathVariable String id,
                            @ApiParam(name = "startDate", value = "start date", defaultValue = "")
                            @RequestParam("startDate") String startDate,
                            @ApiParam(name = "endDate", value = "end date", defaultValue = "")
                            @RequestParam("endDate") String endDate)

其中ApiParam是swagger的参数,RequestParam是REST API,如果使用模型对象替代一个个RequestParam,则更加使得代码精简,然后使用 JSR 303:Bean Validation 对模型对象中字段进行校验:

public class Person {
   @NotNull
   private int id;

   @NotBlank
   @Size(min = 1, max = 20)
   private String firstName;

   @NotBlank
   @Pattern(regexp ="[SOME REGULAR EXPRESSION]")
   private String lastName;

   @Min(0)
   @Max(100)
   private int age;

   //... Constructor, getters, setters, ...
}

使用Swagger和SpringFox文档化Spring Boot REST API

Spring Boot

原文  https://www.jdon.com/springboot/passing-and-validating-requestparam-in.html
正文到此结束
Loading...