Java SpringBoot 使用攔截器作為權(quán)限控制的實(shí)現(xiàn)方法
如何實(shí)現(xiàn)
首先攔截器是屬于web這塊的,那我們需要引入springboot web模塊,具體版本在parent中
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
然后我們?cè)赾onfig目錄下新建interceptor目錄,用來放攔截器
- 我們新建兩個(gè)攔截器,一個(gè)用來登陸攔截,一個(gè)用來進(jìn)行管理員攔截。
- 登陸攔截不必多說,就是判斷除登陸請(qǐng)求外所有請(qǐng)求是否登陸過,沒有我們就截?cái)嗾?qǐng)求,然會(huì)返回失敗狀態(tài)
- 管理員攔截,攔截的是管理員才能訪問的資源,比如用戶管理/權(quán)限管理等,它是登陸攔截放行后才能進(jìn)行的,
- 就像關(guān)卡是一關(guān)一關(guān)的。登陸驗(yàn)證后進(jìn)入管理員驗(yàn)證,判斷該登陸用戶是否具有管理員權(quán)限,若擁有則放行,否則攔截并返回失敗狀態(tài)
- 攔截器的核心是實(shí)現(xiàn) org.springframework.web.servlet.HandlerInterceptor 接口,驗(yàn)證邏輯一般寫在 preHandle 方法中,在請(qǐng)求資源前
- 我的驗(yàn)證邏輯比較簡(jiǎn)單,登陸驗(yàn)證就是從session中取出用戶信息,判斷是否存在,用戶信息是登陸成功時(shí)放入session中的,大家也可以使用JWT驗(yàn)證
- 管理員驗(yàn)證也是從session中取出管理員信息,判斷是否是管理員,管理員信息是登陸成功時(shí)將是否是管理員的信息放入session中的,大家也可以使用JWT驗(yàn)證
登陸攔截器
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; /** * 攔截器,管理員驗(yàn)證 */ @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 { } }
最后我們?cè)赾onfig目錄下新建WebMvcConfig類,用來注冊(cè)攔截器
- 攔截器注冊(cè)類的核心是實(shí)現(xiàn) org.springframework.web.servlet.config.annotation.WebMvcConfigurer 接口
- 實(shí)現(xiàn) addInterceptors 方法,參數(shù) registry 對(duì)象可用來注冊(cè)攔截器
- 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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
實(shí)例解析使用Java實(shí)現(xiàn)基本的音頻播放器的編寫要點(diǎn)
這篇文章主要介紹了使用Java實(shí)現(xiàn)基本的音頻播放器的代碼要點(diǎn)實(shí)例分享,包括音頻文件的循環(huán)播放等功能實(shí)現(xiàn)的關(guān)鍵點(diǎn),需要的朋友可以參考下2016-01-01SpringBoot2.x實(shí)現(xiàn)給Controller的RequestMapping添加統(tǒng)一前綴
這篇文章主要介紹了SpringBoot2.x實(shí)現(xiàn)給Controller的RequestMapping添加統(tǒng)一前綴,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02SpringBoot 使用Mybatis分頁插件實(shí)現(xiàn)詳解
這篇文章主要介紹了SpringBoot 使用Mybatis分頁插件實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10完美解決java.lang.OutOfMemoryError處理錯(cuò)誤的問題
下面小編就為大家?guī)硪黄昝澜鉀Qjava.lang.OutOfMemoryError處理錯(cuò)誤的問題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式
在實(shí)際開發(fā)中經(jīng)常會(huì)遇到在spring容器加載完某個(gè)bean之后,需要執(zhí)行一些業(yè)務(wù)代碼的場(chǎng)景,本文給大家介紹Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式,感興趣的朋友一起看看吧2024-01-01Java中的ArrayList、LinkedList、HashSet等容器詳解
這篇文章主要介紹了Java中的ArrayList、LinkedList、HashSet等容器詳解,集合表示一組對(duì)象,稱為其元素,有些集合允許重復(fù)元素,而另一些則不允許,有些是有序的,有些是無序的,需要的朋友可以參考下2023-08-08