欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot配置拦截器

程序员文章站 2022-07-09 17:31:05
...

层级结构
SpringBoot配置拦截器

1.自定义拦截器类,实现HandlerInterceptor

package com.umi.ga.center_api.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 LogInterceptor implements HandlerInterceptor {
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
//        HttpSession session = request.getSession();
//        System.err.println(session.getId());
//        System.err.println(request.getSession().getId());
        Object centerUser = request.getSession().getAttribute("centeruser");
        String ip = request.getRemoteAddr();
        System.out.println(centerUser+"\t"+ip);
//        if (null == centerUser) {
//            System.err.println("------------------>:权限校验失败");
////            response.sendRedirect("http://www.baidu.com");
//            return false;
//        }
//        System.err.println("------------------>:权限校验成功");
        return true;
    }

}

2.配置拦截规则

创建一个配置类并实现WebMvcConfigurer接口, 覆盖接口中的addInterceptors方法,并为该配置类添加@Configuration注解,标注此类为一个配置类,让Spring Boot 扫描到,这里的操作就相当于SpringMVC的注册拦截器 ,@Configuration就相当于一个applicationContext-mvc.xml

package com.umi.ga.center_api.config;

import com.umi.ga.center_api.interceptor.LogInterceptor;
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 InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //需要拦截的路径,/**表示需要拦截所有请求
//        String[]addPathPatterns={"/**"};
        String[]addPathPatterns={"/loginAccount"};//拦截登录接口
        //不需要拦截的路径
        String [] excludePathPaterns={
                "/static/**"
        };
        //注册一个登录拦截器
        registry.addInterceptor(new LogInterceptor())
                .addPathPatterns(addPathPatterns)
                .excludePathPatterns(excludePathPaterns);
        //注册一个权限拦截器  如果有多个拦截器 ,只需要添加以下一行代码
        //registry.addInterceptor(new LoginInterceptor())
        // .addPathPatterns(addPathPatterns)
        // .excludePathPatterns(excludePathPatterns);

    }
}
相关标签: SpringBoot