日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springBoot 登录拦截器

發布時間:2023/12/13 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springBoot 登录拦截器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、首選創建一個繼承HandlerInterceptor的攔截器

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /*** 攔截器*/ public class MyInterceptor implements HandlerInterceptor{//在請求處理之前進行調用(Controller方法調用之前@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {HttpSession session = httpServletRequest.getSession();String user = (String) session.getAttribute("user"); //獲取登錄的session信息if(user!=null){return true;}else{ httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/index"); //未登錄自動跳轉界面return false;}}//請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后)@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println("postHandle被調用\n");}//在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行(主要是用于進行資源清理工作)@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("afterCompletion被調用\n");} }

  2、繼承WebMvcConfigureAdapter類,覆蓋其addInterceptors接口,注冊自定義的攔截器:

import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration public class WebMvcConfig implements WebMvcConfigurer {/*** 注冊攔截器*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {//addPathPattern后跟攔截地址,excludePathPatterns后跟排除攔截地址registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/index").excludePathPatterns("/login/login"); } }

  

這樣我們就可以在用戶請求到達controller層實現登錄攔截了,所有用戶請求都會被攔截,在prehandle方法進行登錄判斷,返回true則驗證通過,否則失敗

轉載于:https://www.cnblogs.com/cyrfr/p/9132986.html

總結

以上是生活随笔為你收集整理的springBoot 登录拦截器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。