code10validation参数验证

63 阅读1分钟

1在model模块添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2在需要验证的实体类上添加注解实体类

import lombok.Data;
import javax.validation.constraints.NotBlank;

@Data
public class AdUserLoginDto {
    //用户名
    @NotBlank(message = "姓名不能为空")
    private String name;
    //密码
    @NotBlank(message = "密码不能为空")
    private String password;
}

3在Controller的方法上添加注解

@PostMapping("/in")
public ResponseResult in(@Valid @RequestBody AdUserDto dto){
    return adUserService.login(dto);
}

4在前面定义的ExceptionCatch中添加异常处理

package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

@RestControllerAdvice
public class BasicExceptionCatch {


    @ExceptionHandler(RuntimeException.class)
    public ResponseResult runTimeExceptionHandler(RuntimeException e){
        return ResponseResult.error(500,e.getMessage());
    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadExceptionHandler(LeadException e){
        return ResponseResult.error(e.getStatus(),e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult leadExceptionHandler(MethodArgumentNotValidException e){
     //通过e.getBindingResult()得到getBindingResult().getAllErrors()是一个list
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
//        String errMsg = "";
//        for (ObjectError allError : allErrors) {
//            if(errMsg.length()>0) {
//                errMsg += ",";
//            }
//            errMsg += allError.getDefaultMessage();
//        }
        //拿到每个收集起来并用,分割
        String errMsg = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));

        return ResponseResult.error(400,errMsg);
    }
}