在API调用中,有两种传参方式,一种以Bean
的形式,另外一种以附加在URL
上的形式。对于这两种传参方式,Hibernate Validator
都可以提供校验能力,下面就依次说明它们分别如何处理。
1.Bean
-
在
Bean
的属性上添加注解,示例如下:@Data public class Department { @NotBlank private String name; }
-
在
Contoller
层入参Bean
上添加@org.springframework.validation.annotation.Validated
注解,示例如下:@RestController @RequestMapping("/department") public class DepartmentController { @PostMapping @RequestMapping("/add") public ReturnBean add(@Validated @RequestBody Department department) { return ReturnBean.success(); } }
2.URL
-
在
Controller
层添加注解@org.springframework.validation.annotation.Validated
,示例如下:@Validated @RestController @RequestMapping("/department") public class DepartmentController { }
-
在
Controller
层需要校验的URL
参数上加上注解,示例如下:@Validated @RestController @RequestMapping("/department") public class DepartmentController { @RequestMapping("/update/{name}") @PostMapping public ReturnBean update( @Length(min = 1, max = 3) @PathVariable("name") String name, @Length(min = 1, max = 3) @RequestParam(name = "desc", required = false) String desc) { return ReturnBean.success(); } }