SpringMVC 使用JSR-303进行校验Bean Validation-------方法参数、返回值验证

@RestController
@Validated <1>
public class BarController {

    @RequestMapping("/bar")
    public @NotBlank <2> String bar(@Min(18) Integer age <3>) {
        System.out.println("age : " + age);
        return "";
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Map handleConstraintViolationException(ConstraintViolationException cve){
        Set<ConstraintViolation<?>> cves = cve.getConstraintViolations();<4>
        for (ConstraintViolation<?> constraintViolation : cves) {
            System.out.println(constraintViolation.getMessage());
        }
        Map map = new HashMap();
        map.put("errorCode",500);
        return map;
    }

}

<1> 为类添加@Validated注解

<2> <3> 校验方法的返回值和入参

<4> 添加一个异常处理器,可以获得没有通过校验的属性相关信息

基于方法的校验,个人不推荐使用,感觉和项目结合的不是很好。
想了解更多java相关技术,请关注公众号“JavaEE那些事”

扫描下面二维码,更多技术资料等你来拿
这里写图片描述

猜你喜欢

转载自blog.csdn.net/forwujinwei/article/details/79363416