SpringBoot - jSR303校验的Message模板配置
前言
jSR303参数校验可以查看之前的文章 SpringBoot - Bean validation 参数校验,这里介绍消息模板的配置。
具体实现
Message模板配置
- /resources/目录下新增ValidationMessages.properties文件(固定文件名),配置Message
id.valid = id必须是正整数
- 全局异常处理器
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
/**
* @Description 全局异常统一处理
* @author coisini
* @date Aug 9, 2021
* @Version 1.0
*/
@ControllerAdvice
public class GlobalExceptionAdvice1 {
/**
* 注解校验异常处理器
* @param req
* @param e
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(code= HttpStatus.BAD_REQUEST)
@ResponseBody
public UnifyMessage handleConstraintException(HttpServletRequest req, ConstraintViolationException e){
String requestUrl = req.getRequestURI();
String method = req.getMethod();
String message = e.getMessage();
return new UnifyMessage(10001, message, method + " " + requestUrl);
}
}
- 测试用例
@RestController
@RequestMapping("/vaild")
@Validated
public class ValidController {
@GetMapping(value = "/test2/{id}")
public Long test2(@PathVariable @Positive(message = "{id.valid}") Long id) {
return id;
}
}
- 测试结果
模板参数配置
这里自定义一个密码校验注解
- Password 校验注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @Description Password 校验注解
* @author coisini
* @date Aug 17, 2021
* @Version 1.0
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
@Constraint(validatedBy = PasswordValidator.class )
public @interface PasswordValid {
String message() default "字段不符合要求";
int min() default 6;
int max() default 32;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
- Password 校验关联类
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @Description Password 校验关联类
* @author coisini
* @date Aug 17, 2021
* @Version 1.0
*/
public class PasswordValidValidator implements ConstraintValidator<PasswordValid, String> {
private Integer min;
private Integer max;
@Override
public void initialize(PasswordValid constraintAnnotation) {
this.min = constraintAnnotation.min();
this.max = constraintAnnotation.max();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if(StringUtils.isEmpty(s)){
return true;
}
return s.length() >= this.min && s.length() <= this.max;
}
}
- 消息模板配置
user.password = password参数错误:当前值是${validatedValue};最大值应该是{max},最小值应该是{min}
- 测试实体
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
@Getter
@Setter
public class User {
@NotBlank(message = "account不允许为空")
private String account;
@PasswordValid(max=30, message = "{user.password}")
private String password;
}
- 测试用例
@PostMapping(value = "/test3")
public void test3(@RequestBody @Validated User user) {
}
- 测试结果