Springboot配置拦截器(登录拦截)

spring boot拦截器的配置方式和springMVC差不多(springmvc拦截器配置案例)

一、编写拦截器实现类,实现HandlerInterceptor接口

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 统一拦截,判断是否有登录(输入有账号密码,userName就会存储到session)
        Object value = request.getSession().getAttribute("Lotus");
        if (value != null) {
            return true;
        }else {
            request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

二、编写拦截器配置类,实现WebMvcConfigurer接口

@Configuration //一定要加上这个注解,成为Springboot的配置类,不然不会生效
public class WebMvcConfiguration implements WebMvcConfigurer {
 
    @Override   //拦截器配置 
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()) //拦截器注册对象
        .addPathPatterns("/**") //指定要拦截的请求
        .excludePathPatterns("/user/login"); //排除请求

    }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐