Spring Boot 优雅的配置拦截器方式

其实spring boot拦截器的配置方式和springMVC差不多,只有一些小的改变需要注意下就ok了。下面主要介绍两种常用的拦截器:

一、基于URL实现的拦截器:


public class LoginInterceptor extends HandlerInterceptorAdapter{
    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     * 基于URL实现的拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
            //不需要的拦截直接过
            return true;
        } else {
            // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
            System.out.println("====================================");
            return true;
        }
    }
}

关键代码:path.matches(Const.NO_INTERCEPTOR_PATH 就是基于正则匹配的url。


/**
 * @author  BianP
 * @explain 常量类
 */
public class Const {

    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";
    public static final String FIALL = "FIALL";
    /**********************对象和个体****************************/
    public static final String SESSION_USER = "loginedAgent"; // 用户对象
    public static final String SESSION_LOGINID = "sessionLoginID"; // 登录ID
    public static final String SESSION_USERID = "sessionUserID"; // 当前用户对象ID编号

    public static final String SESSION_USERNAME = "sessionUserName"; // 当前用户对象ID编号
    public static final Integer PAGE = 10; // 默认分页数
    public static final String SESSION_URL = "sessionUrl"; // 被记录的url
    public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // 登录页验证码
    // 时间 缓存时间
    public static final int TIMEOUT = 1800;// 秒
    public static final String ON_LOGIN = "/logout.htm";
    public static final String LOGIN_OUT = "/toLogout";
    // 不验证URL anon:不验证/authc:受控制的
    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}

二、基于注解的拦截器

①创建注解:


/**
 * 在需要登录验证的Controller的方法上使用此注解
 */
@Target({ElementType.METHOD})// 可用在方法名上
@Retention(RetentionPolicy.RUNTIME)// 运行时有效
public @interface LoginRequired {

}

②创建拦截器:


public class AuthorityInterceptor extends HandlerInterceptorAdapter{

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①:START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解,需要认证
        if (methodAnnotation != null) {
            // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
            System.out.println("====================================");
            return true;
        }
        return true;
    }
}

三、把拦截器添加到配置中,相当于SpringMVC时的配置文件干的事儿:


/**
 * 和springmvc的webmvc拦截配置一样
 * @author BIANP
 */
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
        registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
     }

     @Bean
     public LoginInterceptor LoginInterceptor() {
         return new LoginInterceptor();
     }

     @Bean
     public AuthorityInterceptor AuthorityInterceptor() {
         return new AuthorityInterceptor();
     }
}

1、一定要加@Configuration  这个注解,在启动的时候在会被加载。

2、有一些教程是用的“WebMvcConfigurerAdapter”,不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter  ,虽然还可以用,但是看起来不好。

3、也有一些教程使用的WebMvcConfigurationSupport,我使用后发现,classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。具体可以原因,大家可以看下源码因为:WebMvcAutoConfiguration上有个条件注解:


@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

所以还是建议使用WebMvcConfigurer, 其实springMVC很多东西,都可以搬到springboot中来使用,只需要把配置文件的模式,改成 对应@Configuration 类就好了。

原文链接:https://my.oschina.net/bianxin/blog/2876640

原文地址:https://www.cnblogs.com/datiangou/p/10245862.html

时间: 2024-07-29 20:53:54

Spring Boot 优雅的配置拦截器方式的相关文章

SpringBoot 优雅的配置拦截器方式

步骤: 1.实现WebMvcConfigurer配置类 2.实现拦截器 3. 把拦截器添加到配置中 4.添加需要拦截的请求 5.添加需要排除的请求 1 package com.zp.springbootdemo.interceptor; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import org

Springboot 系列(六)Spring Boot web 开发之拦截器和三大组件

1. 拦截器 Springboot 中的 Interceptor 拦截器也就是 mvc 中的拦截器,只是省去了 xml 配置部分.并没有本质的不同,都是通过实现 HandlerInterceptor 中几个方法实现.几个方法的作用一一如下. preHandle 进入 Habdler 方法之前执行,一般用于身份认证授权等. postHandle 进入 Handler 方法之后返回 modelAndView 之前执行,一般用于塞入公共模型数据等. afterCompletion 最后处理,一般用于日

spring boot 配置拦截器验证使用 token 登录

1.自定义登录注解 package io.xiongdi.annotation; import java.lang.annotation.*; /** * @author wujiaxing * @date 2019-07-12 * 登录校验 */ @Target(ElementType.METHOD) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Login { } 2.创建 token 实体类 packag

Spring事务配置方式(一) 拦截器方式配置

一.使用<tx:advice>和<aop:config>配置事务 <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSo

spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对照与注意事项

原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory" /> </bean>

spring原拦截器配置与新命名空间mvc:interceptors配置拦截器对比与注意事项

原先,我们是这么配置拦截器的 <bean id="openSessionInViewInterceptor"class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory" /> </bean>

Spring AOP深入理解之拦截器调用

Spring AOP深入理解之拦截器调用 Spring AOP代理对象生成回想 上一篇博客中:深入理解Spring AOP之二代理对象生成介绍了Spring代理对象是怎样生成的,当中重点介绍了JDK动态代理方式,简单回想下代理对象生成过程: 1.上面讲到了两种生成代理对象的方法,一种是通过ProxyFactory,一种是通过ProxyFactoryBean. 第一种获取比較简单,可是须要手工的进行写代码.而另外一种是通过Spring的IOC机制来控制Bean的生成. 2.不管是ProxyFact

白话Spring(中级篇)---拦截器(下)

[一知半解,就是给自己挖坑] 上文我们介绍了Spring中过滤器的基本用法,本文我们来介绍多个拦截器的执行情况,另外一种拦截器的实现方式,以及拦截器与java过滤器的区别.特别的,在本文中,我们将不在演示具体的拦截的实例,请读者们参照上文的实现以及配置方式自行实现. --------------------------------------------------------------------------------------------------------------------

Spring Boot 整合 Shiro ,两种方式全总结!

在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot 整合 Shiro 的话题! 一般来说,Spring Security 和 Shiro 的比较如下: Spring Security 是一个重量级的安全管理框架:Shiro 则是一个轻量级的安全管理框架 Spring Security 概念复杂,配置繁琐:Shiro 概念简单.配置简单 Spring