日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Spring boot拦截器登录检查

發(fā)布時(shí)間:2025/3/20 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring boot拦截器登录检查 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

攔截器

進(jìn)行登錄檢查
從登錄頁面跳轉(zhuǎn)到成功頁面之后

為了防止表單重復(fù)提交
配置視圖映射,利用重定向到成功頁面

此時(shí),在瀏覽器直接輸入,配置的視圖映射地址
也可以直接映射、跳轉(zhuǎn)到成功頁面
登錄頁面,也就失去意義了

添加攔截器,進(jìn)行登錄檢查
通過Session檢查登錄請求

沒有登錄的用戶,不能訪問后臺主頁
當(dāng)?shù)卿洺晒χ?#xff0c;把用戶信息存放到Session中

session.setAttribute("loginUser", username);


LoginHandlerInterceptor
自定義攔截器,必須HandlerInterceptor接口

在目標(biāo)方法執(zhí)行之前,獲取Session
從Session中,獲取用戶登錄信息

如果,已經(jīng)登錄,放行
如果,未登錄,返回登錄頁面

public class LoginHandlerInterceptor implements HandlerInterceptor {//目標(biāo)方法執(zhí)行之前@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object user = request.getSession().getAttribute("loginUser");if(user == null){//未登陸,返回登陸頁面request.setAttribute("msg","沒有權(quán)限請先登陸");request.getRequestDispatcher("/index.html").forward(request,response);return false;}else{//已登陸,放行請求return true;}}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {} }

返回登錄頁面
獲取轉(zhuǎn)發(fā)器,轉(zhuǎn)發(fā)請求到視圖映射器,登錄頁面
request.getRequestDispatcher(“/index.html”).forward(request,response);

顯示錯(cuò)誤消息

request.setAttribute("msg","沒有權(quán)限請先登陸");

注冊攔截器

addInterceptors
攔截除了訪問登錄頁面的所有請求

/**,表示任意路徑下的任意請求
excludePathPatterns,表示排除哪些請求

靜態(tài)資源
之前Spring MVC配置攔截器,需要排除靜態(tài)資源的請求

Spring boot已經(jīng)做好而來靜態(tài)資源映射
不需要進(jìn)行處理,靜態(tài)資源也可以正常訪問

//所有的WebMvcConfigurerAdapter組件都會一起起作用 @Bean //將組件注冊在容器 public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");registry.addViewController("/main.html").setViewName("dashboard");}//注冊攔截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {//super.addInterceptors(registry);//靜態(tài)資源; *.css , *.js//SpringBoot已經(jīng)做好了靜態(tài)資源映射registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html", "/", "/user/login");}};return adapter; }

總結(jié)

以上是生活随笔為你收集整理的Spring boot拦截器登录检查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。