SpringMvc 数据校验
一、定义传递参数
import lombok.Data;
import javax.validation.constraints.*;
@Data
public class Params {
@NotEmpty(message="请输入用户名!")
@Size(min = 2, max = 30, message = "2<长度<30")
private String name;
@Max(value = 150, message = "age应<150") // 数字
@Min(value = 1, message = "age应>1") // 数字
@NotNull(message = "年龄不能为空")
private int size;
@NotNull(message = "邮箱不为空")
@Email(message = "邮件格式不对")
private String email;
}
二、在接收参数位置加 @Valid 注解
@RequestMapping(value="/testvalid",method= RequestMethod.GET)
public String testValid(@Valid Params params){
return "success"
}
三、集中处理失败校验结果
import com.lx.activemq.pojo.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {
/**
* 参数校验结果失败处理
* @param ex
* @param request
* @param response
* @return
*/
@ExceptionHandler({BindException.class})
public ResponseMessage methodDtoNotValidException(BindException ex, HttpServletRequest request, HttpServletResponse response) {
List<FieldError> fieldErrors = ex.getFieldErrors();
for (FieldError fieldError:fieldErrors
) {
log.error(fieldError.getField() + ":" + fieldError.getDefaultMessage());
}
// 将错误的参数的详细信息封装到统一的返回实体
return new ResponseMessage().fail(ex.getAllErrors().get(0).getDefaultMessage());
}
/**
* 全局异常处理
* @param ex
* @param request
* @param response
* @return
*/
@ExceptionHandler({Exception.class})
public ResponseMessage handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
// 将错误的参数的详细信息封装到统一的返回实体
log.error(ex.getLocalizedMessage());
return new ResponseMessage().fail(ex.getMessage());
}
}
自定义校验(以手机号为例)
编写自定义注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD,ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = TelConstraintValidator.class)//验证类
public @interface SelfTel {
String message() default "手机号码不正确";
Class<?> [] groups() default {};
Class<? extends Payload>[] payload()default {};
}
编写验证类(或者写成内部类)
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class TelConstraintValidator implements ConstraintValidator<SelfTel, String> {
@Override
public void initialize(SelfTel constraintAnnotation) {
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (StringUtils.isEmpty(s)) {
return false;
}
return s.matches("^\\d{11}$");
}
}
引用
@ApiOperation("查询用户")
@GetMapping("/{id}")
public ResponseMessage getUser( @PathVariable("id") String id,
@NotEmpty(message="请输入用户名!") String name,
@NotEmpty(message = "手机号不能为空")@SelfTel(message="手机格式不正确")String tel){
return new ResponseMessage().success();
}
注意:
1、处理校验结果绑定异常一定是 springframework的 org.springframework.validation.BindException;
2、注解 @RestControllerAdvice 一定要加