SpringBoot1.x 和 2.x拦截器的使用,通过注解的方式装配到项目中

本文介绍了在SpringBoot 1.x和2.x版本中如何配置拦截器。1.x版本推荐使用`extends WebMvcConfigurerAdapter`,而2.x版本推荐`implements WebMvcConfigurer`。拦截器实现包括`HandlerInterceptor`接口的`preHandle`等方法,并通过注解装配到项目中。配置时需要注意版本选择、注解使用和拦截路径的正确设定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       在SpringBoot 1.x,通常都使用extends WebMvcConfigurerAdapter来实现自定义拦截器。而在springboot 2.x及之后,官方推荐使用implements WebMvcConfigurer来自定义拦截器

        查看springboot版本号:打开项目的pom.xml文件,查看<parent>标签内的springboot版本号。

        

        确定了版本号之后开始写拦截器了,因为我这个是1.5.10版本的,故使用extends WebMvcConfigurerAdapter来实现自定义拦截器。

        1.首先在实现HandlerInterceptor接口,(这个类是对请求路由之前进行验证)。在类中重写起父类方法,preHandle这个类在请求处理之前进行调用(Controller方法调用之前);postHandle这个类在请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后);afterCompletion这个类在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)。我们一般都是重写perHandle这个类,具体代码如下。

package com.lwt.interceptor;

import com.lwt.model.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("调用了:preHandle__HandlerInterceptor");

        /*检验session,判断是否登录*/
        User userInfo = (User) request.getSession().getAttribute("loginUserInfo");
        if (null == userInfo || "".equals(userInfo)) {
            /*重置*/
            response.reset();
            /*拦截后,重定向项目访问路径*/
            response.sendRedirect("/user/toLoginHtml");

            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle__HandlerInterceptor");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion__HandlerInterceptor");
    }
}

    2.将拦截器装配到springboot项目中,并配置拦截路径。

package com.lwt.config;

import com.lwt.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;


/**
 * @Classname LoginConfiguration
 * @Description 拦截器的配置
 * @Date 2020/4/28 21:35
 * @Created by Snow Lee
 */
@Configuration
public class LoginConfiguration extends WebMvcConfigurerAdapter {
    /*注入进来拦截器*/
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("将拦截器注入到springboot中");
        /*为拦截器添加拦截路径*/
        //所有路径都被拦截
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");  
        //添加不拦截路径            
        registry.addInterceptor(loginInterceptor).excludePathPatterns(                         
                "/user/login",
                "/**/*.html");
        /*开放你的登录路径和静态资源路径html,js等等*/
        super.addInterceptors(registry);
    }

}

   在springboot 2.x版中,使用implements WebMvcConfigurer来自定义拦截器。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
</parent>

   实现HandlerInterceptor接口写法是一样的,然后要实现WebMvcConfigurer接口,然后重写addInterceptors方法。

package com.lwt.config;

import com.lwt.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Classname WebConfig
 * @Description 配置拦截信息
 * @Date 2020/4/29 14:36
 * @Created by Snow Lee
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("将拦截信息加载到springboot中");
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(loginInterceptor);
        /*请求拦截,拦截所有*/
        interceptorRegistration.addPathPatterns("/**");

        /*拦截排除*/
        /*开放静态资源*/
        interceptorRegistration.excludePathPatterns("/static/**");
        /*开放其他不需要拦截的请求*/
        interceptorRegistration.excludePathPatterns("/login");
    }
}

       嫌写两个类麻烦,可以把实现HandlerInterceptor接口写成私有内部类,注入的时候不用@Autowired,可以直接在registry.addInterceptor(new  类名);

     注意:1、检查自己的springboot版本号是1.x还是2.x。

                2、注解不要忘记写@Component、@Configuration。

                3、拦截路径不要直接写xxx.html,而是写controller内的路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值