JSR303参数校验与全局异常处理

1、导入依赖


   org.springframework.boot
    spring-boot-starter-validation

2、全局异常处理

package com.itheima.config;
import com.itheima.domain.JSONResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
/**
 * @author: XuXin
 * @date: 2023/9/21
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e) {
        return new JSONResult(02, null, null);
    }
    @ExceptionHandler(BindException.class)
    public JSONResult bindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return new JSONResult(9999, null, message);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public JSONResult constraintViolationExceptionHandle(ConstraintViolationException e) {
        JSONResult jsonResult = new JSONResult();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        constraintViolations.forEach(item -> {
            jsonResult.setMsg(item.getMessage());
        });
        return jsonResult;
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        JSONResult jsonResult = new JSONResult();
        e.getBindingResult().getFieldErrors().forEach(field -> {
            jsonResult.setMsg(field.getDefaultMessage());
        });
        return jsonResult;
    }
}

3、快速校验配置

package com.itheima.config;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/**
 * @author: XuXin
 * @date: 2023/9/21
 */
@Configuration
public class ValidatorConfiguration {
    @Bean
    public Validator validator(){
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                .addProperty( "hibernate.validator.fail_fast", "true" )
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }
}

返回定义JSONResult

package com.itheima.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * @author: XuXin
 * @date: 2023/9/21
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JSONResult {
    private Integer state;
    private Object data;
    private String msg;
}

实体类

package com.itheima.domain;
import lombok.Data;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import java.io.Serializable;
/**
 * @Author CandyWall
 * @Date 2022/1/19--22:58
 * @Description
 */
@Component
@Data
public class Book implements Serializable {
    private Integer id;
    @NotBlank(message = "书名不可为空")
    private String name;
    private String type;
    private String description;
}
package com.itheima.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.Date;
/**
 * @author: XuXin
 * @date: 2023/9/21
 */
@Data
public class ValidationDemo {
    private Integer id;
    @Length(min = 4, max = 8, message = "用户名长度要求在{min}-{max}之间")
    @NotNull(message = "用户名不可为空")
    private String username;
    @Email(message = "邮箱格式错误")
    private String email;
    @Past(message = "出生日期错误")
    private Date birthday;
    @Min(value = 18, message = "未成年不满足注册要求")
    @Max(value = 80, message = "年龄错误")
    private Integer age;
    @Range(min = 0, max = 1, message = "性别选择错误")
    private Integer sex;
    @Valid
    @NotNull(message = "不可为空")
    private Book book;
}

测试

package com.itheima.controller;
import com.itheima.domain.JSONResult;
import com.itheima.domain.ValidationDemo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
 * @author: XuXin
 * @date: 2023/9/21
 */
@RestController
@Validated
public class ValidationController {
    /**
     * @param demo          待校验实体
     * @param
     * @return
     * @Valid 表示对该实体进行校验
     */
    @RequestMapping(value = "validation", method = RequestMethod.POST)
    public JSONResult validate( @Validated @RequestBody ValidationDemo demo) {
        JSONResult jsonResult = new JSONResult();
        jsonResult.setState(11111);
        jsonResult.setData("校验成功");
        jsonResult.setMsg("");
        return jsonResult;
    }
    @GetMapping("/books")
    public JSONResult listParamForJson(@NotBlank(message = "不能为空且size大于0") String name) {
        JSONResult jsonResult = new JSONResult();
        jsonResult.setState(11111);
        jsonResult.setData("校验成功");
        jsonResult.setMsg("");
        return jsonResult;
    }
}

JSR303参数校验与全局异常处理_第1张图片
JSR303参数校验与全局异常处理_第2张图片

你可能感兴趣的:(项目管理,SpringBoot,java,开发语言)