關于自定義過濾器獲取不到session問題
自定義過濾器獲取不到session
根本原因,多個自定義過濾器執(zhí)行順序問題
問題
action請求中request對象為ShiroHttpServletRequest, 可以取到session內容
而在第一個自定義過濾器中request對象為requestfacade,取不到session內容
原因
session由shiro管理,凡是在shiro過濾器順序之前的自定義過濾器都取不到session內容
解決辦法
將shiro過濾器放在第一個位置
登錄攔截器取到的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 渲染了對應的視圖之后執(zhí)行(主要是用于進行資源清理工作) ? ? @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的區(qū)別
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
intellij idea隱藏.iml和.idea等自動生成文件的問題
這篇文章主要介紹了intellij idea隱藏.iml和.idea等自動生成文件的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09關于SpringBoot大文件RestTemplate下載解決方案
這篇文章主要介紹了SpringBoot大文件RestTemplate下載解決方案,最近結合網上案例及自己總結,寫了一個分片下載tuling/fileServer項目,需要的朋友可以參考下2021-10-10