Java SpringBoot 使用攔截器作為權(quán)限控制的實現(xiàn)方法
如何實現(xiàn)
首先攔截器是屬于web這塊的,那我們需要引入springboot web模塊,具體版本在parent中
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
然后我們在config目錄下新建interceptor目錄,用來放攔截器
- 我們新建兩個攔截器,一個用來登陸攔截,一個用來進行管理員攔截。
- 登陸攔截不必多說,就是判斷除登陸請求外所有請求是否登陸過,沒有我們就截斷請求,然會返回失敗狀態(tài)
- 管理員攔截,攔截的是管理員才能訪問的資源,比如用戶管理/權(quán)限管理等,它是登陸攔截放行后才能進行的,
- 就像關(guān)卡是一關(guān)一關(guān)的。登陸驗證后進入管理員驗證,判斷該登陸用戶是否具有管理員權(quán)限,若擁有則放行,否則攔截并返回失敗狀態(tài)
- 攔截器的核心是實現(xiàn) org.springframework.web.servlet.HandlerInterceptor 接口,驗證邏輯一般寫在 preHandle 方法中,在請求資源前
- 我的驗證邏輯比較簡單,登陸驗證就是從session中取出用戶信息,判斷是否存在,用戶信息是登陸成功時放入session中的,大家也可以使用JWT驗證
- 管理員驗證也是從session中取出管理員信息,判斷是否是管理員,管理員信息是登陸成功時將是否是管理員的信息放入session中的,大家也可以使用JWT驗證
登陸攔截器
package com.example.interceptor_demo.config.interceptor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * 攔截器,登錄檢查 */ @Component public class LoginInterceptor implements HandlerInterceptor { @Autowired private HttpSession session; @Autowired private ObjectMapper objectMapper; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object user = session.getAttribute("sessionUser"); if (sessionUser!=null){ return true; }else { Map<String,Object> notLogin = new HashMap<>(); notLogin.put("msg","not login"); notLogin.put("code",403); notLogin.put("data",null); try(PrintWriter printWriter = response.getWriter()){ printWriter.print(objectMapper.writeValueAsString(notLogin)); }catch (Exception e){ e.printStackTrace(); } return false; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
管理員攔截器
package com.example.interceptor_demo.config.interceptor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * 攔截器,管理員驗證 */ @Component public class AdminInterceptor implements HandlerInterceptor { @Autowired private HttpSession session; @Autowired private ObjectMapper objectMapper; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Boolean isAdmin = (Boolean)session.getAttribute("sessionAdmin"); if (isAdmin!=null && isAdmin){ return true; }else { Map<String,Object> notLogin = new HashMap<>(); notLogin.put("msg","no power"); notLogin.put("code",403); notLogin.put("data",null); try(PrintWriter printWriter = response.getWriter()){ printWriter.print(objectMapper.writeValueAsString(notLogin)); }catch (Exception e){ e.printStackTrace(); } return false; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
最后我們在config目錄下新建WebMvcConfig類,用來注冊攔截器
- 攔截器注冊類的核心是實現(xiàn) org.springframework.web.servlet.config.annotation.WebMvcConfigurer 接口
- 實現(xiàn) addInterceptors 方法,參數(shù) registry 對象可用來注冊攔截器
- registry.addInterceptor() 方法用來添加攔截器
- .addPathPatterns() 方法是為該攔截器添加攔截資源路徑
- .excludePathPatterns() 方法是為該攔截器添加要放行的資源路徑
- 其中 * 代表路徑下任意名稱,** 代表任意路徑下任意名稱
package com.example.interceptor_demo.config; import com.example.interceptor_demo.config.interceptor.AdminInterceptor; import com.example.interceptor_demo.config.interceptor.LoginInterceptor; import org.springframework.beans.factory.annotation.Autowired; 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 { @Autowired private LoginInterceptor loginInterceptor; @Autowired private AdminInterceptor adminInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { this.loginInterceptor(registry);//登錄攔截 this.adminInterceptor(registry);//管理員攔截 } private void loginInterceptor(InterceptorRegistry registry){ registry.addInterceptor(loginInterceptor) .addPathPatterns("/**") .excludePathPatterns(//釋放登陸接口 "/login/**" ); } private void adminInterceptor(InterceptorRegistry registry){ registry.addInterceptor(htmlPageInterceptor) .addPathPatterns("/admin/**");//攔截管理員接口 } }
到此這篇關(guān)于Java SpringBoot 使用攔截器作為權(quán)限控制的文章就介紹到這了,更多相關(guān)Java SpringBoot攔截器權(quán)限控制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
實例解析使用Java實現(xiàn)基本的音頻播放器的編寫要點
這篇文章主要介紹了使用Java實現(xiàn)基本的音頻播放器的代碼要點實例分享,包括音頻文件的循環(huán)播放等功能實現(xiàn)的關(guān)鍵點,需要的朋友可以參考下2016-01-01SpringBoot2.x實現(xiàn)給Controller的RequestMapping添加統(tǒng)一前綴
這篇文章主要介紹了SpringBoot2.x實現(xiàn)給Controller的RequestMapping添加統(tǒng)一前綴,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02SpringBoot 使用Mybatis分頁插件實現(xiàn)詳解
這篇文章主要介紹了SpringBoot 使用Mybatis分頁插件實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10完美解決java.lang.OutOfMemoryError處理錯誤的問題
下面小編就為大家?guī)硪黄昝澜鉀Qjava.lang.OutOfMemoryError處理錯誤的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實現(xiàn)方式
在實際開發(fā)中經(jīng)常會遇到在spring容器加載完某個bean之后,需要執(zhí)行一些業(yè)務(wù)代碼的場景,本文給大家介紹Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實現(xiàn)方式,感興趣的朋友一起看看吧2024-01-01Java中的ArrayList、LinkedList、HashSet等容器詳解
這篇文章主要介紹了Java中的ArrayList、LinkedList、HashSet等容器詳解,集合表示一組對象,稱為其元素,有些集合允許重復(fù)元素,而另一些則不允許,有些是有序的,有些是無序的,需要的朋友可以參考下2023-08-08