springboot很好用的自定义验证工具类
请求数据的验证可以用@Valid,但是service层的验证用if 有太繁琐,推荐使用这样的工具类
需要和自定义异常类配合使用
/**
* @author: Gavin
* @created: 2023/4/12 21:06
* @description: 数据验证
**/
public class Assert {
public static void isNull(Object obj, String msg) {
if (obj == null)
throw new StockerException(msg);
}
public static void notNull(Object obj, String msg) {
if (obj != null)
throw new StockerException(msg);
}
public static void isEmpty(CharSequence obj, String msg) {
if(isBlank(obj))
throw new StockerException(msg);
// isTrue(isNotEmpty(array), msg);
}
/***
* 不等于0
* @param num
* @param message
*/
public static void notZero(Integer num, String message) {
if (num.intValue() != 0)
throw new StockerException(message);
}
/***
* 不等于1
* @param num
* @param message
*/
public static void notOne(Integer num, String message) {
if (num.intValue() != 1)
throw new StockerException(message);
}
public static void isZero(Integer num, String message) {
if (num.intValue() == 0)
throw new StockerException(message);
}
public static void isNotZero(Integer num, String message) {
if (num.intValue() != 0)
throw new StockerException(message);
}
/***
* 如果是true 就抛出异常
* @param expression
* @param message
*/
public static void isTrue(boolean expression, String message) {
if (expression)
throw new StockerException(message);
}
public static void isFalse(boolean expression, String message) {
if (!expression)
throw new StockerException(message);
}
public static void isTrue(String message) {
throw new StockerException(message);
}
public static void isEquals(Object obj1, Object obj2, String message) {
if (obj1.equals(obj2))
throw new StockerException(message);
}
public static void notEquals(Object obj1, Object obj2, String message) {
if (!obj1.equals(obj2))
throw new StockerException(message);
}
/**
* obj1大于0bj2
* @param obj1
* @param obj2
* @param message
*/
public static void isGreaterNum(Integer obj1,Integer obj2, String message) {
if (obj1 > obj2)
throw new StockerException(message);
}
public static boolean isBlank(final CharSequence cs) {
if (cs == null) {
return true;
} else {
int l = cs.length();
if (l > 0) {
for(int i = 0; i < l; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
}
return true;
}
}
}
使用案例:
Assert.isNull(v,"wrong account or password");//验证是否为空
Assert.notEquals(v.getPassword(), Md5Utils.encrypt(param.getPassword()),"Wrong account or password");//验证是否相等,验证密码
Assert.notEquals(v.getState(), Constants.Admin.ADMIN_STATUS_NORMAL,"Your account is blocked!");//验证权限


