登錄攔截器取到的session爲空

寫了一個攔截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    /**
     * 註冊攔截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**.html").excludePathPatterns("/Ylogin.html","/Yindex.html","/YRegister.html");
    }
}

判斷有沒有登錄,然後那時候我這邊session.getAttribute(“user”)一直爲空

public class MyInterceptor implements HandlerInterceptor {
    //在請求處理之前進行調用(Controller方法調用之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("開始請求地址攔截");
        //獲取session
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("user") != null)
            return true;

        httpServletResponse.sendRedirect("/Ylogin.html");
            return false;
    }

    //請求處理之後進行調用,但是在視圖被渲染之前(Controller方法調用之後)
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle被調用");
    }

    //在整個請求結束之後被調用,也就是在DispatcherServlet 渲染了對應的視圖之後執行(主要是用於進行資源清理工作)
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion被調用");
    }
}

在另外頁面能得到session的值,但是在攔截器那裏就session爲null,煩了很久,以爲是自己寫錯了攔截器,搞了很久最後才知道,是login.js寫錯了。就是ajax的url寫錯了

$.ajax({
            type: "POST",
            url: "/user/doLogin",
            dataType: "json",
            data:user,
            async:false,
            success: function(res) {}
            })

因爲我以前地址寫的是url:“http://127.0.0.1:8080/user/doLogin”,把前面的ip地址省略就行了,ip地址和localhost的區別

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章