springboot添加拦截器

链接:https://blog.csdn.net/zyp1376308302/article/details/81257510

(侵删)

实现拦截器的两个步骤

  1. 自定义拦截器实现HandlerInterceptor接口
  2. 创建一个配置类继承WebMvcConfigurerAdapter类并重写addInterceptors方法

 

代码

1、自定义拦截器

@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
//    在请求处理之前调用,只有返回true才会执行请求
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//        得到session
        HttpSession session = httpServletRequest.getSession(true);
//        得到对象
        Object admin = session.getAttribute("admin");
//        判断对象是否存在
        if(admin!=null){
            return true;
        }else{
//            不存在则跳转到登录页
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/adminLogin");
            return false;
        }
    }
//    试图渲染之后执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
// 在请求处理之后,视图渲染之前执行 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }

2、自定义配置类继承WebMvcConfigurerAdapter

@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurerAdapter {
    @Autowired
    AdminLoginInterceptor adminLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/login/**"); super.addInterceptors(registry); } }

.addPathPatterns("/admin/**")  :添加需要过滤的路径

.excludePathPatterns("/login/**") :去掉不需要过滤的路径

posted @ 2019-09-26 09:41  小半夏  阅读(679)  评论(0)    收藏  举报