spring中自定义valid验证器

直接来步骤

第一步:增加验证依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

第二步:创建annotation注解目录

第三步:开始创建验证器以验证长度为例

@Constraint  中指定进行验证的验证方法类

@Documented
@Target(value = {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = LengthValidator.class)
public @interface LengthValid {
    /** 报错信息 */
    String message() default "长度不符合规范";

    /** 最小值 */
    int min() default 0;

    /** 最大值 */
    int max() default Integer.MAX_VALUE;

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

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

第四步:创建验证方法类

public class LengthValidator implements ConstraintValidator<LengthValid,Object> {
    private LengthValid annotation;
    @Override
    public void initialize(LengthValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if( null == value ){
            return true;
        }

        try {
            int len = String.valueOf(value).length();
            if( len >= annotation.min() && len <= annotation.max()){
                return true;
            }
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
        return false;
    }
}

 基于以上的四步,我们就已经创建完成了自定义的注解验证。接下来是如何使用:

仅仅只需要在实体属性上增加相关的注解就可以使用了

@LengthValid(min=2,max = 100,message = "姓名只支持最短2位最长100位")
private String name;

以上就完成了自定义验证类了。


下面在给大家提供一个枚举值验证的方法,不需要的可以不往下看了

增加自定义枚举验证类

下面直接上注解和处理类及使用方法。

一、注解:

@Documented
@Target(value = {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValidator.class)
public @interface EnumValid {
    /** 报错信息 */
    String message() default "枚举字符不存在";

    /** 枚举类 */
    Class<?> clazz();

    /** 枚举获取值方法 */
    String method();

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

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

二、处理类:

public class EnumValidator implements ConstraintValidator<EnumValid,Object> {
    private EnumValid annotation;
    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        //如果传的参数为null 不需要验证枚举中是否存在
        if( null == value ){
            return true;
        }
        //获取枚举类数据
        Object[] enumConstants = annotation.clazz().getEnumConstants();

        //获取方法
        try {
            //获取枚举类获取code的方法
            Method method = annotation.clazz().getMethod(annotation.method());
            for (Object enumConstant : enumConstants) {
                //循环枚举类数据,并通过method反射获取与value判断是否相等
                if(value.equals(method.invoke(enumConstant))){
                    return true;
                }
            }
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
        return false;
    }
}

三、使用方法:

//clazz代表的是枚举类  method是枚举类提供的获取方法 getCode获取枚举类中的code值
@EnumValid(clazz = TypeEnum.class,message = "类型不存在",method = "getCode")
private Integer type;
### 创建自定义拦截器捕获无有效会话 为了在Spring框架中创建一个能够处理没有有效会话情况的自定义拦截器,可以通过实现`HandlerInterceptor`接口并重写其方法来达成目标。当检测到不存在有效的会话时,在`preHandle`方法内执行特定逻辑[^2]。 下面是一个具体的例子: ```java import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @Component public class SessionValidationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { HttpSession session = request.getSession(false); // 如果session为空,则认为是没有登录的状态 if (session == null || session.getAttribute("user") == null) { try { // 设置响应状态码为未授权 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 可选:返回JSON格式的消息给前端 response.setContentType("application/json;charset=UTF-8"); response.getWriter().write("{\"message\":\"No valid session\"}"); // 返回false阻止后续处理器继续执行 return false; } catch (IOException e) { throw new RuntimeException(e); } } // 存在一个有效的会话,允许请求继续前进 return true; } } ``` 此代码片段展示了如何构建一个简单的拦截器类 `SessionValidationInterceptor` 来验证是否存在有效的用户会话。如果发现当前HTTP请求缺少合法的会话信息,则设置相应的HTTP响应头,并向客户端发送一条消息表示存在认证失败的情况;反之则让请求正常流转下去。 为了让上述拦截器生效,还需要将其注册至应用程序配置文件之中。对于Spring Boot项目而言,这通常意味着要编写如下所示的一个配置类: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { private final SessionValidationInterceptor sessionValidationInterceptor; @Autowired public WebConfig(SessionValidationInterceptor sessionValidationInterceptor) { this.sessionValidationInterceptor = sessionValidationInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sessionValidationInterceptor).addPathPatterns("/secure/**"); } } ``` 这段配置指定了哪些路径下的资源应该受到该拦截器的影响——这里假设只有以 `/secure/` 开始的URL才需要检查是否有有效的会话。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值