springboot JSR303 参数校验使用

1. springboot 项目 引入过web ,不需要额外引入。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.参数为类的,在类属性上加入 javax.validation.constraints 包下的各种验证注解(例如:@NotNull(message = "ID不能为空!") ).

3.Controller 类中在需要验证的方法属性前添加注解(@Valid ),然后在类 或 方法上添加  @Validated

若不是对象  :也可在 属性上添加 @验证注解(

 @Valid @NotNull(message = "内容不能为空")

区别:https://www.cnblogs.com/leeego-123/p/10821028.html

4.验证不通过错误信息返回



package com.dingjia.jiaxin.handler;

import com.alibaba.fastjson.JSON;
import com.dingjia.jiaxin.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice
public class ExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(ExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public Result handleError(Throwable e) {
        if (e instanceof MethodArgumentNotValidException) {
            // 处理请求参数格式错误 @RequestBody 校验失败后抛出异常
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            BindingResult bindingResult = validException.getBindingResult();
            String message = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("、"));
            return Result.builder().status(1001).msg(message).build();
        } else if (e instanceof ConstraintViolationException) {
            // 处理请求参数格式错误 @RequestParam 校验失败后抛出异常
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
            String message = constraintViolationException.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("、"));
            return Result.builder().status(1001).msg(message).build();
        } else if (e instanceof BindException) {
            //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出异常
            BindException bindException = (BindException) e;
            String message = bindException.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("、"));
            return Result.builder().status(1001).msg(message).build();
        } else if (e instanceof ResultRuntimeExemption) {
            //系统自定义异常抛出
            return Result.builder().status(500).msg(e.getMessage()).build();
        } else {
              //其它错误
            return Result.builder().status(500).msg("服务内部错误,请稍后重试").build();
        }

    }

}

5.联级验证(验证对象中包含其他对象 以及 一对多 或 多对一)

在验证 验证对象中的属性上 添加 @Valid ,list 也可以在泛型里加@Valid 

//或 @Valid 
private List<@Valid UserInfo> UserInfoList;

6.在service 中添加校验,不是在实现类中添加而是在接口中添加

@Validated
@Service
public class ServiceImpl implements Service{    
   @Validated(groups“分组”)
   public void   method (@Valid Object obj){
}

注:Result 类为自定义统一返回对象 

//状态码
private int status;
//提示信息
private String msg;
//数据
private Object data;

//根据需求添加其他属性

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值