这个实际上是延伸自我的另一篇文章Java开发中参数判空操作;
近期写到groovy
项目的时候发现java
的并不适用, 于是写了此篇文章;
/**
* @Author OGtwelve
* @Date 2024/3/26
* @Description: controller层参数校验工具类
*/
class ValidationUtils {
static void validateFields(dto, Map<Closure, String> validations) {
validations.each { closure, errorMessage ->
def value = closure(dto)
if (value == null ||
(value instanceof String && value.trim().isEmpty()) ||
(value instanceof Integer && value <= 0) ||
(value instanceof Long && value <= 0L) ||
(value instanceof BigDecimal && value <= BigDecimal.ZERO) ||
(value instanceof Double && value <= 0.0) ||
(value instanceof Float && value <= 0.0) ||
(value instanceof Byte && value <= 0) ||
(value instanceof Short && value <= 0)) {
throw new BusinessException(errorMessage)
}
}
}
}
那么下面是在controller
中使用的效果:
情况1 : 固定字段的判空
static void inputJudge(UserDetail dto) {
Map<Closure, String> validations = [
{ it.name }: "用户名不能为空",
{ it.phone }: "手机号不能为空"
]
ValidationUtils.validateFields(dto, validations)
Optional.ofNullable(dto.phone).ifPresent(phone -> {
if (phone.length() != 11) {
throw new IllegalArgumentException("请输入正确长度手机号");
}
if (!PhoneNumberUtils.isPhone(phone)) {
throw new IllegalArgumentException("请输入正确格式手机号");
}
});
// 邮箱格式校验
Optional.ofNullable(dto.email).ifPresent(email -> {
if (!EmailValidator.validateEmail(email)) {
throw new IllegalArgumentException("请输入正确格式邮箱");
}
});
// TODO 行业表校验
}
........
@RequestMapping("addUserInfo")
AjaxResult addUserInfo(@RequestBody UserDetail dto) {
inputJudge(dto)
UserInfo userInfo = new UserInfo()
....
return ....
}
情况2 : 动态字段的判空
private static void dynamicFieldJudge(UserDetail dto, Map<Closure, String> fieldValidations) {
ValidationUtils.validateFields(dto, fieldValidations)
}
@RequestMapping("findUserInfoByPhone")
AjaxResult findUserInfoByPhone(@RequestBody UserDetail dto) {
dynamicFieldJudge(dto, [ { it.phone }: "手机号不能为空"])
.....
}
@RequestMapping("findUserInfoByAccountId")
AjaxResult findUserInfoByAccountId(@RequestBody UserDetail dto) {
dynamicFieldJudge(dto, [ { it.accountId }: "账号id不能为空" , { it.userinfoId }: "用户id不能为空"])
......
}
那么以上就是使用我的工具在groovy里判空啦;