spring boot

SpringBoot2.x 的参数验证& Web全局异常处理

2020-08-30  本文已影响0人  骑蚂蚁上高速_jun

Springboot 的参数验证 一般使用 javax.validation.constraints. 包中的注解类进行验证
安装spring-boot-starter-validation 验证依赖
spring-boot-starter-validation 就是使用 Hibernate Validator 框架来提供 Java Bean 验证功能。
在pom.xml 文件添加 验证依赖

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

1.1 在控制器中快速验证的方法

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RestController
public class Index
{
    @GetMapping("/validate")
    public String validate(
        // 字符串长度验证
        @Size(min = 1,max = 10,message = "姓名长度必须为1到10")
        @RequestParam() String name,
        // 范围验证
        @Min(value = 10,message = "年龄最小为10")
        @Max(value = 100,message = "年龄最大为100")
        @RequestParam(defaultValue = "101") int age,
        // 正则验证
        @Pattern(regexp = "^[0-9]{6}$", message = "商品编号不正确")
        @RequestParam() String goodNo
    ){
        return name+":"+age+":"+goodNo;
    }
}

1.2 独立验证类中 验证,可采用分组验证 (功能强大, 建议实际生产使用)
层次如图


image.png

定义分组层

package cn.waimaolang.demo.request.home.interfaces;

public interface Group1 {
}

定义验证层

package cn.waimaolang.demo.request.home;

import lombok.Data;
import javax.validation.constraints.*;
import cn.waimaolang.demo.request.home.interfaces.Group1;

@Data
public class IndexRequest {
    
    
    @NotNull(message ="name 不能为空",groups = {Group1.class}) // 声明分组验证
    private String name;

    @NotBlank(message ="password 不能为空")
    private String password;

    public String getName() {
        return name;
    }

    public String getPassword() {
        return password;
    }

    public String getEmail() {
        return email;
    }

    @Email(message ="email 格式非法")
    @NotNull(message ="email 不能为空")
    private String email;
}

2 . 在控制器中使用验证

package cn.waimaolang.demo.controller.home;

import cn.waimaolang.demo.mapper.StudentMapper;
import cn.waimaolang.demo.params.QueueParams;
import cn.waimaolang.demo.pojo.Students;
import cn.waimaolang.demo.request.home.IndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.waimaolang.demo.request.home.interfaces.Group1;

@RestController
@RequestMapping(value = "home")
public class Index
{
    @Autowired
    StudentMapper studentMapper;

    @PostMapping("/addName")
    public int validate1(
        // 下面这一句 是 仅对 IndexRequest 类中声明 Group1.class 参数进行验证
        @RequestBody @Validated(Group1.class) IndexRequest indexRequest
    ){
        Students students= new Students("0001","wangjun","男","500","广东 东莞");
        int r= studentMapper.storeStudents(students); // 使用 mybatis 插入数据
        String name = indexRequest.getName();
        
        int t = 1/0;
        return students.getId(); // 返回得到 数据表的自增主键id
    }

    @Autowired
    QueueParams queueParams;
}
  1. 参数验证 全局异常处理
package cn.waimaolang.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * web 全局异常处理
 */
@RestControllerAdvice
public class GlobalWebException
{
    /**
     * 前端参数异常时,返回 验证层中声明的错误信息
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException ex){
        Map<String,Object> result = new HashMap<String,Object>(3);

        List<FieldError> errors = ex.getBindingResult().getFieldErrors();//得到所有的参数异常
        //String message = errors.get(0).getDefaultMessage();
        //int count= ex.getBindingResult().getErrorCount();//得到异常参数的个数
        result.put("code",-1);
        result.put("msg",errors.get(0).getDefaultMessage()); // 返回第一个异常参数信息
        return new ResponseEntity(result ,HttpStatus.BAD_REQUEST);
    }

    /**
     * 运行时异常 用于处理 RuntimeException 异常
     */
    @ExceptionHandler(value = {RuntimeException.class})
    public ResponseEntity<Object> handleBindException(
            RuntimeException ex
    ){
        System.out.println(ex.getClass());
        System.out.println(ex.getMessage());
        Map<String,Object> result = new HashMap<String,Object>(2);
        result.put("code",-2);
        result.put("msg",ex.getMessage());
        return new ResponseEntity(result,HttpStatus.EXPECTATION_FAILED);
    }

    /**
     * 系统产生的未知 异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    ResponseEntity exception(Exception ex){
        Map<String,Object> result = new HashMap<String,Object>(3);
        result.put("code",-3);
        result.put("msg",ex.getMessage());
        result.put("data",null);
        System.out.println("系统异常...");
        return new ResponseEntity(result ,HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

上一篇下一篇

猜你喜欢

热点阅读