您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關SpringBoot使用HandlerInterceptor攔截器的方法,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
前言
平常項目開發過程中,會遇到登錄攔截
,權限校驗
,參數處理
,防重復提交
等問題,那攔截器
就能幫我們統一處理這些問題。
一、實現方式
1.1 自定義攔截器
自定義攔截器,即攔截器的實現類,一般有兩種自定義方式:
定義一個類,實現org.springframework.web.servlet.HandlerInterceptor
接口。
定義一個類,繼承已實現了HandlerInterceptor接口的類,例如org.springframework.web.servlet.handler.HandlerInterceptorAdapter
抽象類。
1.2 添加Interceptor攔截器到WebMvcConfigurer配置器中
自定義配置器,然后實現WebMvcConfigurer配置器。
以前一般繼承org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
類,不過SrpingBoot 2.0以上WebMvcConfigurerAdapter類就過時了。有以下2中替代方法:
直接實現org.springframework.web.servlet.config.annotation.WebMvcConfigurer
接口。(推薦)
繼承org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
類。但是繼承WebMvcConfigurationSupport會讓SpringBoot對mvc的自動配置失效。不過目前大多數項目是前后端分離,并沒有對靜態資源有自動配置的需求,所以繼承WebMvcConfigurationSupport也未嘗不可。
二、HandlerInterceptor 方法介紹
preHandle
:預處理,在業務處理器處理請求之前被調用,可以進行登錄攔截,編碼處理、安全控制、權限校驗等處理;
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
postHandle
:后處理,在業務處理器處理請求執行完成后,生成視圖之前被調用。即調用了Service并返回ModelAndView,但未進行頁面渲染,可以修改ModelAndView,這個比較少用。
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { }
afterCompletion
:返回處理,在DispatcherServlet完全處理完請求后被調用,可用于清理資源等。已經渲染了頁面。
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { }
三、攔截器(Interceptor)實現
3.1 實現HandlerInterceptor
此攔截器演示了通過注解形式,對用戶權限進行攔截校驗。
package com.nobody.interceptor; import com.nobody.annotation.UserAuthenticate; import com.nobody.context.UserContext; import com.nobody.context.UserContextManager; import com.nobody.exception.RestAPIError; import com.nobody.exception.RestException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Description * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Slf4j @Component public class UserPermissionInterceptor implements HandlerInterceptor { private UserContextManager userContextManager; @Autowired public void setContextManager(UserContextManager userContextManager) { this.userContextManager = userContextManager; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { log.info(">>> UserPermissionInterceptor preHandle -- "); if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; // 獲取用戶權限校驗注解(優先獲取方法,無則再從類獲取) UserAuthenticate userAuthenticate = handlerMethod.getMethod().getAnnotation(UserAuthenticate.class); if (null == userAuthenticate) { userAuthenticate = handlerMethod.getMethod().getDeclaringClass() .getAnnotation(UserAuthenticate.class); } if (userAuthenticate != null && userAuthenticate.permission()) { // 獲取用戶信息 UserContext userContext = userContextManager.getUserContext(request); // 權限校驗 if (userAuthenticate.type() != userContext.getType()) { // 如若不拋出異常,也可返回false throw new RestException(RestAPIError.AUTH_ERROR); } } } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { log.info(">>> UserPermissionInterceptor postHandle -- "); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { log.info(">>> UserPermissionInterceptor afterCompletion -- "); } }
3.2 繼承HandlerInterceptorAdapter
package com.nobody.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /** * @Description * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Slf4j @Component public class UserPermissionInterceptorAdapter extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { log.info(">>> UserPermissionInterceptorAdapter preHandle -- "); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { log.info(">>> UserPermissionInterceptorAdapter postHandle -- "); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { log.info(">>> UserPermissionInterceptorAdapter afterCompletion -- "); } }
四、配置器(WebMvcConfigurer)實現
4.1 實現WebMvcConfigurer(推薦)
package com.nobody.config; import com.nobody.context.UserContextResolver; import com.nobody.interceptor.UserPermissionInterceptor; import com.nobody.interceptor.UserPermissionInterceptorAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; /** * @Description * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Configuration public class WebAppConfigurer implements WebMvcConfigurer { private UserPermissionInterceptor userPermissionInterceptor; private UserPermissionInterceptorAdapter userPermissionInterceptorAdapter; private UserContextResolver userContextResolver; @Autowired public void setUserPermissionInterceptor(UserPermissionInterceptor userPermissionInterceptor) { this.userPermissionInterceptor = userPermissionInterceptor; } @Autowired public void setUserPermissionInterceptorAdapter( UserPermissionInterceptorAdapter userPermissionInterceptorAdapter) { this.userPermissionInterceptorAdapter = userPermissionInterceptorAdapter; } @Autowired public void setUserContextResolver(UserContextResolver userContextResolver) { this.userContextResolver = userContextResolver; } @Override public void addInterceptors(InterceptorRegistry registry) { // 可以添加多個攔截器,一般只添加一個 // addPathPatterns("/**") 表示對所有請求都攔截 // .excludePathPatterns("/base/index") 表示排除對/base/index請求的攔截 // 多個攔截器可以設置order順序,值越小,preHandle越先執行,postHandle和afterCompletion越后執行 // order默認的值是0,如果只添加一個攔截器,可以不顯示設置order的值 registry.addInterceptor(userPermissionInterceptor).addPathPatterns("/**") .excludePathPatterns("/base/index").order(0); // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**") // .excludePathPatterns("/base/index").order(1); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { resolvers.add(userContextResolver); } }
4.2 繼承WebMvcConfigurationSupport
package com.nobody.config; 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.WebMvcConfigurationSupport; import com.nobody.interceptor.UserPermissionInterceptor; import com.nobody.interceptor.UserPermissionInterceptorAdapter; /** * @Description * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Configuration public class WebAppConfigurerSupport extends WebMvcConfigurationSupport { @Autowired private UserPermissionInterceptor userPermissionInterceptor; // @Autowired // private UserPermissionInterceptorAdapter userPermissionInterceptorAdapter; @Override public void addInterceptors(InterceptorRegistry registry) { // 可以添加多個攔截器,一般只添加一個 // addPathPatterns("/**") 表示對所有請求都攔截 // .excludePathPatterns("/base/index") 表示排除對/base/index請求的攔截 registry.addInterceptor(userPermissionInterceptor).addPathPatterns("/**") .excludePathPatterns("/base/index"); // registry.addInterceptor(userPermissionInterceptorAdapter).addPathPatterns("/**") // .excludePathPatterns("/base/index"); } }
五、其他主要輔助類
5.1 用戶上下文類
package com.nobody.context; import com.nobody.enums.AuthenticationTypeEnum; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * @Description 用戶上下文 * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Getter @Setter @ToString public class UserContext { // 用戶名稱 private String name; // 用戶ID private String userId; // 用戶類型 private AuthenticationTypeEnum type; }
5.2 校驗訪問權限注解
package com.nobody.context; import com.nobody.enums.AuthenticationTypeEnum; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * @Description 用戶上下文 * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Getter @Setter @ToString public class UserContext { // 用戶名稱 private String name; // 用戶ID private String userId; // 用戶類型 private AuthenticationTypeEnum type; }
5.3 用戶上下文操作類
package com.nobody.context; import com.nobody.enums.AuthenticationTypeEnum; import com.nobody.exception.RestAPIError; import com.nobody.exception.RestException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Objects; import java.util.UUID; /** * @Description 用戶上下文操作類 * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Component public class UserContextManager { private static final String COOKIE_KEY = "__userToken"; // @Autowired // private RedisService redisService; /** * 獲取用戶上下文信息 * * @param request * @return */ public UserContext getUserContext(HttpServletRequest request) { String userToken = getUserToken(request, COOKIE_KEY); if (!StringUtils.isEmpty(userToken)) { // 從緩存或者第三方獲取用戶信息 // String userContextStr = redisService.getString(userToken); // if (!StringUtils.isEmpty(userContextStr)) { // return JSON.parseObject(userContextStr, UserContext.class); // } // 因為演示,沒集成Redis,故簡單new對象 UserContext userContext = new UserContext(); userContext.setName("Mr.nobody"); userContext.setUserId("0000001"); userContext.setType(AuthenticationTypeEnum.ADMIN); return userContext; } throw new RestException(RestAPIError.AUTH_ERROR); } public String getUserToken(HttpServletRequest request, String cookieKey) { Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { if (Objects.equals(cookie.getName(), cookieKey)) { return cookie.getValue(); } } } return null; } /** * 保存用戶上下文信息 * * @param response * @param userContextStr */ public void saveUserContext(HttpServletResponse response, String userContextStr) { // 用戶token實際根據自己業務進行生成,此處簡單用UUID String userToken = UUID.randomUUID().toString(); // 設置cookie Cookie cookie = new Cookie(COOKIE_KEY, userToken); cookie.setPath("/"); response.addCookie(cookie); // redis緩存 // redisService.setString(userToken, userContextStr, 3600); } }
5.4 方法參數解析器類
package com.nobody.context; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Component; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import javax.servlet.http.HttpServletRequest; /** * @Description 對有UserContext參數的接口,進行攔截注入用戶信息 * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @Component @Slf4j public class UserContextResolver implements HandlerMethodArgumentResolver { @Autowired private UserContextManager userContextManager; @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { log.info(">>> resolveArgument -- begin..."); HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); // 從緩存獲取用戶信息賦值到接口參數中 return userContextManager.getUserContext(request); } /** * 只對UserContext參數進行攔截賦值 * * @param methodParameter * @return */ @Override public boolean supportsParameter(MethodParameter methodParameter) { if (methodParameter.getParameterType().equals(UserContext.class)) { return true; } return false; } }
六、測試驗證
package com.nobody.controller; import com.alibaba.fastjson.JSON; import com.nobody.annotation.UserAuthenticate; import com.nobody.context.UserContext; import com.nobody.context.UserContextManager; import com.nobody.enums.AuthenticationTypeEnum; import com.nobody.pojo.model.GeneralResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; /** * @Description * @Author Mr.nobody * @Date 2020/10/25 * @Version 1.0 */ @RestController @RequestMapping("user") public class UserController { @Autowired private UserContextManager userContextManager; @GetMapping("login") public GeneralResult<UserContext> doLogin(HttpServletResponse response) { UserContext userContext = new UserContext(); userContext.setUserId("0000001"); userContext.setName("Mr.nobody"); userContext.setType(AuthenticationTypeEnum.ADMIN); userContextManager.saveUserContext(response, JSON.toJSONString(userContext)); return GeneralResult.genSuccessResult(userContext); } @GetMapping("personal") @UserAuthenticate(permission = true, type = AuthenticationTypeEnum.ADMIN) public GeneralResult<UserContext> getPersonInfo(UserContext userContext) { return GeneralResult.genSuccessResult(userContext); } }
啟動服務后,在瀏覽器先調用personal接口,因為沒有登錄,所以會報錯沒有權限:
控制臺輸出:
啟動服務后,在瀏覽器先訪問login接口進行登錄,再訪問personal接口,驗證通過,正確返回用戶信息:
以上就是SpringBoot使用HandlerInterceptor攔截器的方法,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。