1. hibernate validator注解在web项目中常常用到,是一个很好用的字段校验器,能够对前端传入的参数进行判断,如是否为空,是否知足正则规定的格式等等。前端
2. 假设有一个业务场景,须要判断前端传入的用户是否存在,而项目中有不少地方会用到此判断,此时能够构造一个自定义校验器进行字段校验,在须要的时候只须要加上此注解便可。java
3. controller接口web
package net.mshome.twisted.tmall.common.controller;
import net.mshome.twisted.tmall.common.dto.UserAddDTO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
*
* 前端控制器
*
*
* @author tangjizhou
* @since 2019-05-04
*/
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@PostMapping("/register")
public void register(@RequestBody @Valid UserAddDTO userAddDTO) {
}
}
4. 前端传入的参数,注意此处的自定义注解 @UserFieldspring
package net.mshome.twisted.tmall.common.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.mshome.twisted.tmall.common.annotation.UserField;
import javax.validation.constraints.NotNull;
/**
* @author tangjizhou
* @date 2019-06-20
* @description 前端post传入参数
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserAddDTO {
/**
* 假设此处可填写多个用户,以逗号隔开
*/
@UserField(message = "填写的用户{}不存在")
@NotNull(message = "请填写用户")
private String usernames;
}
5. 自定义注解apache
package net.mshome.twisted.tmall.common.annotation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
/**
* @author tangjizhou
* @date 2019-06-20
* @description 验证用户是否存在注解
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Constraint(validatedBy = UserFieldValidator.class)
public @interface UserField {
String message() default "";
String defaultMessage = "用户{}不存在";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
6. 实现注解功能mybatis
package net.mshome.twisted.tmall.common.annotation;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.mshome.twisted.tmall.common.entity.User;
import net.mshome.twisted.tmall.common.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* @author tangjizhou
* @date 2019-06-20
* @description 验证用户是否存在
*/
@Component
public class UserFieldValidator implements ConstraintValidator {
private String defaultMessage;
@Autowired
private IUserService userService;
@Override
public void initialize(UserField constraint) {
this.defaultMessage = constraint.defaultMessage;
}
@Override
public boolean isValid(String usernames, ConstraintValidatorContext context) {
// 若是什么都没有输入,则不判断,直接返回
if (StringUtils.isEmpty(usernames)) {
return true;
}
// 判断用户是否存在
String illegalUsernames = Arrays.stream(usernames.split(",")).distinct().map(username -> {
int count = userService.count(new QueryWrapper<>(User.builder().username(username).build()));
return count == 0 ? username : null;
}).filter(StringUtils::isNotEmpty).collect(Collectors.joining(","));
// 全部用户都存在,返回true
if (StringUtils.isBlank(illegalUsernames)) {
return true;
}
/* ************************ 若是存在非法用户****************************/
// 禁用直接返回默认的message
context.disableDefaultConstraintViolation();
// 获取注解配置的message
String messageTemplate = context.getDefaultConstraintMessageTemplate();
messageTemplate = StringUtils.isEmpty(messageTemplate) ? defaultMessage : messageTemplate;
// 构造返回信息,进行占位符替换
context.buildConstraintViolationWithTemplate(StringUtils.replace(messageTemplate, "{}", illegalUsernames))
.addConstraintViolation();
return false;
}
}