002 validation自定义校验器

文章目录

pom.xml

xml 复制代码
        <!-- 引入validation依赖,完成校验 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.4.5</version>
        </dependency>

ValidatorUtil.java

java 复制代码
package com.example.util;




import org.junit.jupiter.api.Test;
import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 完成一些校验,比如手机号格式是否正确
 * 正则
 */
public class ValidatorUtil {

    //校验手机号码的正则表达式
    private static final Pattern mobile_pattern = Pattern.compile("^[1][3-9][0-9]{9}$");

    //编写方法
    public static boolean isMobile(String mobile) {
        if(!StringUtils.hasText(mobile)) {
            return false;
        }

        Matcher matcher = mobile_pattern.matcher(mobile);
        return matcher.matches();
    }


    //测试校验方法
    @Test
    public void t1() {
        String mobile = "0133333333";
        System.out.println(isMobile(mobile));


        String mobile2 = "13333333333";
        System.out.println(isMobile(mobile2));
    }


}

IsMobileValidator.java

java 复制代码
package com.example.validator;

import org.springframework.util.StringUtils;
import com.example.util.ValidatorUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;



//拟定注解 IsMobile   的校验规则, 可以自己根据业务需求来编写..
public class IsMobileValidator
        implements ConstraintValidator<IsMobile, String> {
    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        //初始化
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        //必填
        if (required) {
            return ValidatorUtil.isMobile(value);
        } else {//非必填
            if (!StringUtils.hasText(value)) {
                return true;
            } else {
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}

IsMobile.java

java 复制代码
package com.example.validator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * IsMobile: 开发一个自定义的注解
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
    String message() default "手机号码格式错误";

    boolean required() default true;

    Class<?>[] groups() default { };//默认参数

    Class<? extends Payload>[] payload() default { };//默认参数
}

LoginVo.java

java 复制代码
package com.example.vo;


import com.example.validator.IsMobile;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;

/**
 * 接收用户登录时,发送的信息(moblie,password)
 */
@Data
public class LoginVo {


    //对LoginVo的属性值进行约束
    @NotNull
    @IsMobile
    private String mobile;

    @NotNull
    @Length(min = 32)
    private String password;

}

LoginController.java

java 复制代码
package com.example.controller;


import com.example.service.UserService;
import com.example.vo.LoginVo;
import com.example.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {


    //装配UserService
    @Resource
    private UserService userService;

    //编写方法,可以进入到登录页面

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";//到templates/login.html
    }


    //处理用户登录请求
    @RequestMapping("/doLogin")
    @ResponseBody
    public RespBean doLogin(@Valid LoginVo loginVo,
                            HttpServletRequest request,
                            HttpServletResponse response) {

        System.out.println("controller层:"+loginVo);

        //log.info("{}",loginVo);

        return userService.doLogin(loginVo,request,response);
    }

}
相关推荐
宋冠巡19 天前
Spring Boot Validation 封装自定义校验注解和校验器(validation-spring-boot-starter)
spring boot·参数校验·validation
初晴~1 个月前
【spring】参数校验Validation
java·c++·spring boot·后端·python·spring·validation
春哥的魔法书4 个月前
Spring Validation 校验 ( 二 )
java·后端·spring·validation
春哥的魔法书4 个月前
Spring Validation 校验 ( 一 )
java·spring boot·spring·validation
伊织code5 个月前
Llama - Validation
大模型·llama·eval·loss·validation·perplexity·holdout
人间有清欢9 个月前
kotlin使用validation注解无效
spring boot·kotlin·validation
奇遇少年10 个月前
Jakarta Bean Validation
java·数据验证·validation
huangxr8746687391 年前
Spring Boot编写自定义校验注解
spring boot·springmvc·valid·validation·校验器
gc_22991 年前
学习.NET验证模块FluentValidation的基本用法(续3:ASP.NET Core中的调用方式)
asp.net core·fluent·validation