[Java]Spring/SpringBoot拦截过滤器的实现HandlerInterceptorAdapter

2021-03-08 1105点热度 0人点赞 0条评论

前言

在前一篇文章 SpringBoot启动后执行和关闭前执行代码介绍了Spring启动和关闭的时候执行代码,还有一种情况,需要每一次请求的时候做一些操作,例如检查请求是否合法(Token是否过期,是否合法)等

这种用到了HandlerInterceptor(SpringBoot)/HandlerInterceptor(Spring)

SpringBoot下的实现

第一步,新建一个过滤器类继承

HandlerInterceptor

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 根据request来确定是否需要拦截本次请求(比如根据request得到header里面约定的token等等),如果需要拦截,返回false,否则返回true
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) {

    }
}

第二部,把MyInterceptor配置到拦截器里面去,新建(如果已存在就改写)一个类继承WebMvcConfigurerAdapter

@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器,并配置需要拦截的路径
        registry.addInterceptor(new MyInterceptor().addPathPatterns("/admin/**");
        super.addInterceptors(registry);
    }
}

Spring下的实现

Spring下是继承HandlerInterceptorAdapter,如下:

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 根据request来确定是否需要拦截本次请求(比如根据request得到header里面约定的token等等),如果需要拦截,返回false,否则返回true
        return true;
    }


}

注册拦截器,我们假设是用xml写的配置文件(spring-servlet.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!--其他配置省略-->
    <!--注册拦截器,并配置需要拦截的路径-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/admin/**"/>
            <bean class="com.terrynow.test.interceptor.MyInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论