SpringMVC利用全局异常数据校验

2019-08-26  本文已影响0人  艾特小师叔

异常拦截-数据校验

SSM框架集成数据校验:

导入相关jar包

SSM集成所有jar包+以下jar包

classmate-1.3.4.jar
jboss-logging-3.3.3.Final.jar
validation-api-2.0.1.Final.jar
hibernate-validator-6.0.17.Final.jar

数据校验工具类

package com.sxt.common.validate;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.springframework.validation.BindException;
import com.sxt.common.CodeMsg;
import com.sxt.common.exception.BussiException;

public class ValidatorUtils {
    private static Validator validator;
    
    static {
        //构建Validator 对象
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws BindException  校验不通过,则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws BussiException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();

            for(ConstraintViolation<Object> constraint:  constraintViolations){
                msg.append(constraint.getMessage());
                break;
            }
            throw new BussiException(CodeMsg.PARAM_VALIDATE_ERROR,msg.toString());
        }
    }
}


业务信息枚举

package com.sxt.common;
/**
 * 业务信息枚举
 * @author mrt
 *
 */
public enum CodeMsg {
    //成功
    SUCCESS(200,"SUCCESS"),
    //数据校验
    PARAM_VALIDATE_ERROR(400100003,"参数校验异常:"),
    
    
    int code;
    
    String msg;
    
    CodeMsg(int code,String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

统一JSON结果类:

package com.sxt.common;

import java.io.Serializable;

/**
 * 用于返回json 数据
 * @author mrt
 *
 */
public class Result implements Serializable {
    private static final long serialVersionUID = -5948622670638601979L;
    //业务响应码
    private int code ;
    //业务消息
    private String msg;
    //业务数据
    private Object data;

    public Result() {
        this.code = CodeMsg.SUCCESS.getCode();
        this.msg = CodeMsg.SUCCESS.getMsg();
    }
    
    public Result(Object data) {
        this.code = CodeMsg.SUCCESS.getCode();
        this.msg = CodeMsg.SUCCESS.getMsg();
        this.data = data;
    }
    
    public Result(CodeMsg codeMsg) {
        this.code = codeMsg.getCode();
        this.msg = codeMsg.getMsg();
    }
    
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}

业务异常类:

package com.sxt.common.exception;

import com.sxt.common.CodeMsg;

/**
 * 业务异常类
 * @author mrt
 *
 */
public class BussiException extends RuntimeException{
    private static final long serialVersionUID = 1L;

    private CodeMsg codeMsg;

    public BussiException(CodeMsg codeMsg,String msg) {
        super(codeMsg.toString());
        this.codeMsg = codeMsg;
        codeMsg.setMsg(msg);
    }

    public CodeMsg getCodeMsg() {
        return codeMsg;
    }
}

全局业务异常拦截

package com.sxt.common.hanlder;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxt.common.Result;
import com.sxt.common.exception.BussiException;

@ControllerAdvice
public class GlobalExceptionHandler {
    
    
     /**
     * 只处理业务异常   非业务异常考虑使用跳转页面
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(BussiException.class)
    @ResponseBody
    public Object allExceptionHandler(HttpServletRequest request, Exception exception) {
        exception.printStackTrace();
        //判断是否是业务异常
        BussiException ex = (BussiException)exception;
        return new Result(ex.getCodeMsg());
    }


}

注意:

扫描业务异常拦截类上的注解

接收数据实体类:

package com.sxt.form;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

public class UserForm {
    
    @Min(value = 0,message = "id最小值为0")
    @Max(value = 20,message = "id最大值为20")
    @NotNull(message = "id值不能为空")
    private Integer id;
    
    @Length(min = 10,max=20,message = "name 最小10位数 最大20位")
    @NotBlank(message = "name值不能为空")
    private String name;
    
    @Range(min=1,max=2,message="性别的值只能是1  或者  2")
    private String sex;
    
    
    public UserForm() {}
    

    public UserForm(int id, String name, String sex) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
    }




    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", sex=" + sex + "]";
    }
    

}

示例controller方法:

    /**
     * 使用userForm接收前端数据 
     * 然后统一进行校验
     * @param userForm
     * @return
     */
    @RequestMapping("/test.do")
    @ResponseBody
    public String test(UserForm userForm) { 
        
        ValidatorUtils.validateEntity(userForm);
        return "success";
    }

附录:Validation 内置注解

@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits(integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
Hibernate Validator 附加的 constraint:

@NotBlank 验证字符串非null,且长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
上一篇下一篇

猜你喜欢

热点阅读