springboot项目做个拦截器

生成一个类

@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    protected org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler)throws Exception {

        HttpSession session = request.getSession(true);
        Object username=session.getAttribute("userguid");
        if(null!=username) {//已登录
            return true;
        }else {//未登录
            //直接重定向到登录页面
            //response.sendRedirect(request.getContextPath()+"/wechatplatformuser/loginRBAC.html");
            return false;
        }
    }
}

然后在你的配置类中加上

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns("/**") 表示拦截所有的请求,
        // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
        registry.addInterceptor(userLoginInterceptor).addPathPatterns("/**").excludePathPatterns( "/static/**","/login/logins","不需要拦截的路径");
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章