SpringBoot配置拦截器

实现自定义拦截器只需要3步:
1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。
2、创建一个Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法。
2、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。

实现HandlerInterceptor接口

package com.fluently.blog.Interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object obj, Exception err)
            throws Exception {
        System.out.println("============================拦截器关闭==============================");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object obj, ModelAndView mav) throws Exception {
        System.out.println("============================执行处理完毕==============================");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
        //获取session里的登录状态值
        //        String str = (String) request.getSession().getAttribute("isLogin");
        //        //如果登录状态不为空则返回true,返回true则会执行相应controller的方法
        //        if (str != null) {
        //            return true;
        //        }
        //        //如果登录状态为空则重定向到登录页面,并返回false,不执行原来controller的方法
        //        response.sendRedirect("/backend/loginPage");
        //        return false;
        System.out.println("============================拦截器启动==============================");
        System.out.println("拦截器");
        return true;
    }

}

继承WebMvcConfigurerAdapter并添加拦截器

package com.fluently.blog.Interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class InterceptorConfigurerAdapter extends WebMvcConfigurerAdapter {
    /**
     * 该方法用于注册拦截器
     * 可注册多个拦截器,多个拦截器组成一个拦截器链
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 添加路径
        // excludePathPatterns 排除路径
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

你可能感兴趣的:(SpringBoot配置拦截器)