1. 程式人生 > >Spring mvc 引數校驗

Spring mvc 引數校驗

2個版本(註解和介面),另外加一個自定義註解

一.註解版

1.引入pom

        <!--校驗-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId
>
<artifactId>hibernate-validator</artifactId> </dependency>

2.實體類

import javax.validation.constraints.Max;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;

public
class User { @NotBlank(message="名字不能為空") @Size(min=1, max=4) private String userName; @Max(value=120,message="年齡最大不能查過120") private int age; @NotBlank(message="郵箱不能為空") @Email(message="郵箱格式錯誤") private String email; public String getUserName() { return userName; } public
void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }

3.測試

    @RequestMapping("/login")
    @ResponseBody
    @RequestInfo(description = "cache-page-測試1")
    public String testValid(@Valid User user, BindingResult result)   {
        if (result.hasErrors()) {
            List<ObjectError> errorList = result.getAllErrors();
            for (ObjectError error : errorList) {
                System.out.println(error.getDefaultMessage());
            }
        }

        return "register";
    }

二.註解版

1.引入pom

        <!--校驗-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

2.實體類

public class User {

    private String userName;
    private int age;
    private String email;


    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }


}

3.校驗類

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.oppo.paas.pcache.service.annotation.User;

/**
 * 校驗介面版(需要對應@Validated)
 * 可以自定義校驗規則
 * @author 80218857
 *
 */

public class UserValidator implements Validator {

    @Override
    public boolean supports(Class<?> arg0) {
        return arg0.equals(User.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "userName", "user.userName.required", "使用者名稱不能為空");
        ValidationUtils.rejectIfEmpty(errors, "email", "user.email.required", "郵箱不能為空");
        User user = (User) target;
        int length = user.getUserName().length();
        if (length > 4) {
            errors.rejectValue("userName", "user.userName.too_long", "使用者名稱不能超過{4}個字元");
        }
        int index = user.getEmail().indexOf("@");
        if (index == -1) {
            errors.rejectValue("email", "user.email.invalid_email", "郵箱格式錯誤");
        }
    }

}

4.測試

@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserValidator());
    }

    @RequestMapping("/login2")
    @ResponseBody
    @RequestInfo(description = "cache-page-測試1")
    public String testValid(@Validated User user, BindingResult result) {
        if (result.hasErrors()) {
            List<ObjectError> errorList = result.getAllErrors();
            for (ObjectError error : errorList) {
                System.out.println(error.getDefaultMessage());
            }
        }

        return "register";
    }

三.自定義註解

1.自定義@Ip

    import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.oppo.paas.pcache.web.validator.IpValidator;
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.RetentionPolicy.RUNTIME;

/**
 * IP驗證
 *
 * @author Hero
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = IpValidator.class )
public @interface Ip {

    String message() default "IP格式不正確";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };


}

校驗類

import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.example.demo.validator.annotation.Ip;

public class IpValidator implements ConstraintValidator<Ip, String> {

    private String ipReg = "^(([1-9]|([1-9]\\d)|(1\\d\\d)|(2([0-4]\\d|5[0-5])))\\.)(([1-9]|([1-9]\\d)|(1\\d\\d)|(2([0-4]\\d|5[0-5])))\\.){2}([1-9]|([1-9]\\d)|(1\\d\\d)|(2([0-4]\\d|5[0-5])))$";// ip的正則表示式
    private Pattern ipPattern = Pattern.compile(ipReg);

    @Override
    public void initialize(Ip constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null)
            return true;
        return ipPattern.matcher(value).matches();
    }

}

2.使用@Ip

同一
例:
    @Ip(message = "IP格式錯誤")
    private String ip;