springboot 参数校验使用示例

接收基本类型参数

在使用多个基本类型接收参数时,@Validated 要写在 controller 上,写在方法、方法参数前都不行,@Valid 无法使用,如果只是验证 @NotNull,可以直接在方法参数前使用 @RequestParam

@RestController
@RequestMapping("/test")
@Validated
public class TestController {
    @PostMapping("/singleField")
    public String singleField(@NotNull String age, @RequestParam(value = "name") String name) {
        return name + age;
    }
}

使用封装类接收参数

使用封装类接收参数时,使用 @Validated@Valid 效果是一样的,这两个都只能写在方法参数前才能生效,如果类的数据也是类,并且需要嵌套校验,则需要在属性上使用 @Valid 注解。在使用 @RequestBody 接收数据时校验方法相同

@Data
public class Album {
    @NotNull
    private Integer musicCount;
    @NotNull
    private String[] musics;
    @NotNull @Size(min = 2) @Valid
    private List<Person> musicians;
    @NotNull @Size(max = 1) @Valid
    private Person[] people;
    @NotNull @Valid
    private Person person;
}
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private ObjectMapper json;

    @PostMapping("/test")
    public String test(@Validated Album album) throws JsonProcessingException {
        return json.writeValueAsString(album);
    }
}

接收基本类型数组和基本类型集合

使用规则和接收基本类型参数一样,@Validated 要写在 Controller 上,写在方法、方法参数前都不行,@Valid 无法使用

@RestController
@RequestMapping("/test")
@Validated
public class TestController {
    @Resource
    private ObjectMapper json;

    @PostMapping("/array")
    public String array(@NotNull @Size(max = 1) String[] strs,@NotNull Integer[] ints) throws JsonProcessingException {
        return json.writeValueAsString(strs)+" "+json.writeValueAsString(ints);
    }
    
	@PostMapping("/test")
    public String test(@RequestBody @Size(min = 2) List<String> strs) throws JsonProcessingException {
        return json.writeValueAsString(strs);
    }
}

接收对象类型数组和集合

注入时必须使用 @RequestBody ,校验时需要在 Controller 上写 @Validated 并且在方法参数前使用 @Valid

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值