校验非空的注解@NotNull如何取得自定义的message

2022-07-21,,,,

目录
  • 校验非空的注解@notnull如何取得自定义的message
  • @notnull 等注解的简单使用
    • controller层

校验非空的注解@notnull如何取得自定义的message

由于项目表单需要校验字段过多,一个一个去判空太麻烦,所以用了@notnull注解,字段为空会抛出methodargumentnotvalidexception异常。

接下来要取得@notnull(message=“自定义异常”)里的message内容给前端显示

直接贴上代码:

public string  getmessage(methodargumentnotvalidexception exception){
string message =  exception.getbindingresult().getfielderror().getdefaultmessage();
return message;
}

用法:定义一个全局异常处理

一旦发生该类异常,就会捕捉处理,返回给前端信息,返回类result要根据自己项目业务需要来定义

@notnull 等注解的简单使用

springboot 2.3.0 以后不会自动引入jar包,所以要添加以下maven

2.3以前则不需要引入maven包

<dependency>
 <groupid>org.springframework.boot</groupid>
 <artifactid>spring-boot-starter-validation</artifactid>
</dependency>

注册一个账号, 有账号+密码

前端会做一个判空,但是后端同时也要做一个判空,防止url直接访问

这时后端的代码通常是

if(name!=null){
 return "账号不能为空,请重新输入";
}
else if(password!=null){
 return "密码不能为空,请重新输入";
}

这样就会显得特别low,而且极不美观

这时候就要用到一个注解@notnull

简单举例说明:

@data
public class userinfo {
    @notnull(message = "姓名不能为null")
    private string name;
    @max(value = 30,message = "年龄不能超过30")
    private integer age;    
    private integer password;
    private string sex;
}

controller层

简单举例说明

@restcontroller
public class testcontroller {
    @requestmapping("test1")
    public object test1(@valid @requestbody userinfo userinfo,bindingresult result){
  //判断有没有异常错误,如果有则返回默认消息
       if (result.haserrors()){
            string defaultmessage = result.getfielderror().getdefaultmessage();
            return defaultmessage;
        }
        //打印一下数据结构
        system.out.println(userinfo); 
        //如果没有错误,返回注册成功
        return "注册成功";
    }
  }

用postman 传入json 参数,name有值,年龄超过30岁

返回我们的设定

name 为null 同理,会按顺序判断!

但是问题又来了,难道我们每个controller层的方法里面都要写一个判断方法?

当然不,这时候就要用到全局异常类了

起一个类

@controlleradvice
public class controllerexception {
    @responsebody
    @exceptionhandler(methodargumentnotvalidexception.class)
    public object handlevalidexception(methodargumentnotvalidexception e) {
    
        //将错误信息返回给前台
        return e.getbindingresult().getfielderror().getdefaultmessage();
    }
}

为了有所区分,写下另一个访问方法

 @requestmapping("test2")
    public object test1(@valid @requestbody userinfo userinfo){
        
        system.out.println(userinfo);
        return "注册成功";
    }

这时候我们传入参数

到此结束,再也不用写一堆各种判空了

附上 部分注解

  • @null 限制只能为null
  • @notnull 限制必须不为null
  • @assertfalse 限制必须为false
  • @asserttrue 限制必须为true
  • @decimalmax(value) 限制必须为一个不大于指定值的数字
  • @decimalmin(value) 限制必须为一个不小于指定值的数字
  • @digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
  • @future 限制必须是一个将来的日期
  • @max(value) 限制必须为一个不大于指定值的数字
  • @min(value) 限制必须为一个不小于指定值的数字
  • @past 限制必须是一个过去的日期
  • @pattern(value) 限制必须符合指定的正则表达式
  • @size(max,min) 限制字符长度必须在min到max之间
  • @past 验证注解的元素值(日期类型)比当前时间早
  • @notempty 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
  • @notblank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@notempty,@notblank只应用于字符串且在比较时会去除字符串的空格
  • @email 验证注解的元素值是email,也可以通过正则表达式和flag指定自定义的email格式

二次更新:所有的controller 都写这样的代码就要封装成异常类

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.responsebody;
/**
 * @author :lsy
 * @date :created in 2020/7/23 10:13
 * @modified by:
 */
@controlleradvice
public class controllerexception {
    private final static string exception_msg_key = "exception message : ";
    @responsebody
    @exceptionhandler(methodargumentnotvalidexception.class)
    public object handlevalidexception(methodargumentnotvalidexception e) {
        //日志记录错误信息
       // log.error(objects.requirenonnull(e.getbindingresult().getfielderror()).getdefaultmessage());
        //将错误信息返回给前台
       // return baseresult.fail(500, objects.requirenonnull(e.getbindingresult().getfielderror()).getdefaultmessage());
        return e.getbindingresult().getfielderror().getdefaultmessage();
    }
}

不需要写bindingresult 也可以返回message

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

《校验非空的注解@NotNull如何取得自定义的message.doc》

下载本文的Word格式文档,以方便收藏与打印。