SpringBoot使用JSR303做引數校驗
阿新 • • 發佈:2018-12-26
1. 實體
public class User {
@NotNull
private Integer id;
@NotNull
private String name;
@NotNull
@Length(min=6)
private String password;
@NotNull
@IsPhone //自定義的校驗
private String phone;
}
2. Controller中使用
@PostMapping(value="login")
public String login(@Valid User user) {
}
3. 自定義校驗
註解IsPhone
判斷是否為手機號
package com.pibigstar.springboot.validator;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {PhoneValidator.class})
public @interface IsPhone {
boolean required() default true;
String message() default "手機號不合法"; //錯誤預設提示資訊
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
4. 實現具體校驗類
package com.pibigstar.springboot.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 手機號碼驗證者
* @author pibigstar
*
*/
public class PhoneValidator implements ConstraintValidator<IsPhone,String>{
private boolean requeired;
@Override
public void initialize(IsPhone constraintAnnotation) {
requeired = constraintAnnotation.required();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (requeired) {
return isPhone(value);
}else {
//phone 不是必須
if (value==null||value.length()==0) {
return true;
}else {
return isPhone(value);
}
}
}
private boolean isPhone(String phone) {
//以1開頭,後面跟10個整數,一共11位
Pattern phonePattern = Pattern.compile("1\\d{10}");
if (phone==null||phone.length()<=0) {
return false;
}else {
Matcher matcher = phonePattern.matcher(phone);
return matcher.matches();
}
}
}
5. 對引數不通過進行統一捕獲
引數驗證不通過後統一格式返回給前端頁面
package com.pibigstar.springboot.exception;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pibigstar.springboot.domain.result.MyResponse;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(value=Exception.class)
public MyResponse exceptionHandler(HttpServletRequest request,Exception e) {
//引數校驗異常
if (e instanceof BindException) {
BindException exception = (BindException) e;
List<ObjectError> allErrors = exception.getAllErrors();
ObjectError objectError = allErrors.get(0);
String defaultMessage = objectError.getDefaultMessage();
return MyResponse.error(defaultMessage);
}else {
//其他異常
return MyResponse.error(e);
}
}
}