SpringBoot 統一功能處理
前言
接下來是 Spring Boot 統⼀功能處理模塊了,也是 AOP 的實戰環節,要實現的課程⽬標有以下 3 個:
- 統⼀⽤戶登錄權限驗證
- 統⼀數據格式返回
- 統⼀異常處理
接下我們⼀個⼀個來看。
一、用戶登錄權限效驗
⽤戶登錄權限的發展從之前每個⽅法中⾃⼰驗證⽤戶登錄權限,到現在統⼀的⽤戶登錄驗證處理,它是⼀個逐漸完善和逐漸優化的過程。
1.1 最初的用戶登錄驗證
我們先來回顧⼀下最初⽤戶登錄驗證的實現⽅法:
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 某⽅法 1
*/
@RequestMapping("/m1")
public Object method(HttpServletRequest request) {
// 有 session 就獲取,沒有不會創建
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
// 說明已經登錄,業務處理
return true;
} else {
// 未登錄
return false;
}
}
/**
* 某⽅法 2
*/
@RequestMapping("/m2")
public Object method2(HttpServletRequest request) {
// 有 session 就獲取,沒有不會創建
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
// 說明已經登錄,業務處理
return true;
} else {
// 未登錄
return false;
}
}
// 其他⽅法...
}
從上述代碼可以看出,每個⽅法中都有相同的⽤戶登錄驗證權限,它的缺點是:
- 每個⽅法中都要單獨寫⽤戶登錄驗證的⽅法,即使封裝成公共⽅法,也⼀樣要傳參調⽤和在⽅法中進⾏判斷。
- 添加控制器越多,調⽤⽤戶登錄驗證的⽅法也越多,這樣就增加了後期的修改成本和維護成本。
- 這些⽤戶登錄驗證的⽅法和接下來要實現的業務⼏何沒有任何關聯,但每個⽅法中都要寫⼀遍。
所以提供⼀個公共的 AOP ⽅法來進⾏統⼀的⽤戶登錄權限驗證迫在眉睫。
1.2 Spring AOP 用戶統一登錄驗證的問題
說到統⼀的⽤戶登錄驗證,我們想到的第⼀個實現⽅案是 Spring AOP 前置通知或環繞通知來實現,具體實現代碼如下:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UserAspect {
// 定義切點⽅法 controller 包下、⼦孫包下所有類的所有⽅法
@Pointcut("execution(* com.example.demo.controller..*.*(..))")
public void pointcut(){ }
// 前置⽅法
@Before("pointcut()")
public void doBefore(){
}
// 環繞⽅法
@Around("pointcut()")
public Object doAround(ProceedingJoinPoint joinPoint){
Object obj = null;
System.out.println("Around ⽅法開始執⾏");
try {
// 執⾏攔截⽅法
obj = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("Around ⽅法結束執⾏");
return obj;
}
}
如果要在以上 Spring AOP 的切⾯中實現⽤戶登錄權限效驗的功能,有以下兩個問題:
- 沒辦法獲取到 HttpSession 對象。
- 我們要對⼀部分⽅法進⾏攔截,⽽另⼀部分⽅法不攔截,如註冊⽅法和登錄⽅法是不攔截的,這樣的話排除⽅法的規則很難定義,甚⾄沒辦法定義。
那這樣如何解決呢?
1.3 Spring 攔截器
對於以上問題 Spring 中提供了具體的實現攔截器:HandlerInterceptor,攔截器的實現分爲以下兩個步驟:
- 創建⾃定義攔截器,實現 HandlerInterceptor 接⼝的 preHandle(執⾏具體⽅法之前的預處理)⽅法。
- 將⾃定義攔截器加⼊ WebMvcConfigurer 的 addInterceptors ⽅法中。
具體實現如下。
補充 過濾器:
過濾器是 Web 容器提供的。觸發的時機比攔截器更靠前,Spring 初始化前就執行了,所以並不能處理用戶登錄權限效驗等問題。
1.3.1 準備工作
package com.example.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@RequestMapping("/login")
public boolean login(HttpServletRequest request,
String username, String password) {
// // 1.非空判斷
// if (username != null && username != "" &&
// password != null && username != "") {
// // 2.驗證用戶名和密碼是否正確
// }
// 1.非空判斷
if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) {
// 2.驗證用戶名和密碼是否正確
if ("admin".equals(username) && "admin".equals(password)) {
// 登錄成功
HttpSession session = request.getSession();
session.setAttribute("userinfo", "admin");
return true;
} else {
// 用戶名或密碼輸入錯誤
return false;
}
}
return false;
}
@RequestMapping("/getinfo")
public String getInfo() {
log.debug("執行了 getinfo 方法");
return "執行了 getinfo 方法";
}
@RequestMapping("/reg")
public String reg() {
log.debug("執行了 reg 方法");
return "執行了 reg 方法";
}
}
1.3.2 自定義攔截器
接下來使⽤代碼來實現⼀個⽤戶登錄的權限效驗,⾃定義攔截器是⼀個普通類,具體實現代碼如下:
package com.example.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 登錄攔截器
*/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 登錄判斷業務
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
return true;
}
log.error("當前用戶沒有訪問權限");
response.setStatus(401);
return false;
}
}
返回 boolean 類型。
相當於一層安保:
爲 false 則不能繼續往下執行;爲 true 則可以。
1.3.3 將自定義攔截器加入到系統配置
將上⼀步中的⾃定義攔截器加⼊到系統配置信息中,具體實現代碼如下:
package com.example.demo.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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration // 一定不要忘記
public class MyConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**") // 攔截所有請求
.excludePathPatterns("/user/login") // 排除不攔截的 url
// .excludePathPatterns("/**/*.html")
// .excludePathPatterns("/**/*.js")
// .excludePathPatterns("/**/*.css")
.excludePathPatterns("/user/reg"); // 排除不攔截的 url
}
}
或者:
package com.example.demo.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class AppConfig implements WebMvcConfigurer {
// 不攔截的 url 集合
List<String> excludes = new ArrayList<String>() {{
add("/**/*.html");
add("/js/**");
add("/editor.md/**");
add("/css/**");
add("/img/**"); // 放行 static/img 下的所有文件
add("/user/login"); // 放行登錄接口
add("/user/reg"); // 放行註冊接口
add("/art/detail"); // 放行文章詳情接口
add("/art/list"); // 放行文章分頁列表接口
add("/art/totalpage"); // 放行文章分頁總頁數接口
}};
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置攔截器
InterceptorRegistration registration =
registry.addInterceptor(loginInterceptor);
registration.addPathPatterns("/**");
registration.excludePathPatterns(excludes);
}
}
如果不注入對象的話,addInterceptor() 的參數也可以直接 new 一個對象:
@Configuration // 一定不要忘記
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") // 攔截所有請求
.excludePathPatterns("/user/login") // 排除不攔截的 url
// .excludePathPatterns("/**/*.html")
// .excludePathPatterns("/**/*.js")
// .excludePathPatterns("/**/*.css")
// .excludePathPatterns("/**/*.jpg")
// .excludePathPatterns("/**/login")
.excludePathPatterns("/user/reg"); // 排除不攔截的 url
}
}
其中:
- addPathPatterns:表示需要攔截的 URL,“**” 表示攔截任意⽅法(也就是所有⽅法)。
- excludePathPatterns:表示需要排除的 URL。
說明:以上攔截規則可以攔截此項⽬中的使⽤ URL,包括靜態⽂件 (圖⽚⽂件、JS 和 CSS 等⽂件)。
1.4 攔截器實現原理
正常情況下的調⽤順序:
然⽽有了攔截器之後,會在調⽤ Controller 之前進⾏相應的業務處理,執⾏的流程如下圖所示:
1.4.1 實現原理源碼分析
所有的 Controller 執⾏都會通過⼀個調度器 DispatcherServlet 來實現,這⼀點可以從 Spring Boot 控制檯的打印信息看出,如下圖所示:
⽽所有⽅法都會執⾏ DispatcherServlet 中的 doDispatch 調度⽅法,doDispatch 源碼如下:
protected void doDispatch(HttpServletRequest request, HttpServletResponse
response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
ModelAndView mv = null;
Object dispatchException = null;
try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
if (mappedHandler == null) {
this.noHandlerFound(processedRequest, response);
return;
}
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.g
etHandler());
String method = request.getMethod();
boolean isGet = HttpMethod.GET.matches(method);
if (isGet || HttpMethod.HEAD.matches(method)) {
long lastModified = ha.getLastModified(request, mapped
Handler.getHandler());
if ((new ServletWebRequest(request, response)).checkNo
tModified(lastModified) && isGet) {
return;
}
}
// 調⽤預處理【重點】
if (!mappedHandler.applyPreHandle(processedRequest, respon
se)) {
return;
}
// 執⾏ Controller 中的業務
mv = ha.handle(processedRequest, response, mappedHandler.g
etHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
this.applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response,
mv);
} catch (Exception var20) {
dispatchException = var20;
} catch (Throwable var21) {
dispatchException = new NestedServletException("Handler di
spatch failed", var21);
}
this.processDispatchResult(processedRequest, response, mappedH
andler, mv, (Exception)dispatchException);
} catch (Exception var22) {
this.triggerAfterCompletion(processedRequest, response, mapped
Handler, var22);
} catch (Throwable var23) {
this.triggerAfterCompletion(processedRequest, response, mapped
Handler, new NestedServletException("Handler processing failed", var23));
}
} finally {
if (asyncManager.isConcurrentHandlingStarted()) {
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processe
dRequest, response);
}
} else if (multipartRequestParsed) {
this.cleanupMultipart(processedRequest);
}
}
}
從上述源碼可以看出在開始執⾏ Controller 之前,會先調⽤ 預處理⽅法 applyPreHandle,⽽
applyPreHandle ⽅法的實現源碼如下:
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex
= i++) {
// 獲取項⽬中使⽤的攔截器 HandlerInterceptor
HandlerInterceptor interceptor = (HandlerInterceptor)this.intercep
torList.get(i);
if (!interceptor.preHandle(request, response, this.handler)) {
this.triggerAfterCompletion(request, response, (Exception)null
);
return false;
}
}
return true;
}
從上述源碼可以看出,在 applyPreHandle 中會獲取所有的攔截器 HandlerInterceptor 並執⾏攔截器中
的 preHandle ⽅法,這樣就會咱們前⾯定義的攔截器對應上了,如下圖所示:
此時⽤戶登錄權限的驗證⽅法就會執⾏,這就是攔截器的實現原理。
1.4.2 攔截器小結
通過上⾯的源碼分析,我們可以看出,Spring 中的攔截器也是通過動態代理和環繞通知的思想實現的,⼤體的調⽤流程如下:
1.5 擴展:統一訪問前綴添加
所有請求地址添加 api 前綴:
@Configuration
public class AppConfig implements WebMvcConfigurer {
// 所有的接⼝添加 api 前綴
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("api", c -> true);
}
}
其中第⼆個參數是⼀個表達式,設置爲 true 表示啓動前綴。
二、統一異常處理
統⼀異常處理使⽤的是 @ControllerAdvice + @ExceptionHandler 來實現的,@ControllerAdvice 表示控制器通知類,@ExceptionHandler 是異常處理器,兩個結合表示當出現異常的時候執⾏某個通知,也就是執⾏某個⽅法事件,具體實現代碼如下:
package com.example.demo.config;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
/**
* 統一處理異常
*/
@ControllerAdvice
public class ErrorAdive {
@ExceptionHandler(Exception.class)
@ResponseBody
public HashMap<String, Object> exceptionAdvie(Exception e) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", "-1");
result.put("msg", e.getMessage());
return result;
}
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public HashMap<String, Object> arithmeticAdvie(ArithmeticException e) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", "-2");
result.put("msg", e.getMessage());
return result;
}
}
方法名和返回值可以⾃定義,重要的是 @ControllerAdvice 和 @ExceptionHandler 註解。
以上⽅法表示,如果出現了異常就返回給前端⼀個 HashMap 的對象,其中包含的字段如代碼中定義的那樣。
我們可以針對不同的異常,返回不同的結果,⽐以下代碼所示:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
public Object exceptionAdvice(Exception e) {
HashMap<String, Object> result = new HashMap<>();
result.put("success", -1);
result.put("message", "總的異常信息:" + e.getMessage());
result.put("data", null);
return result;
}
@ExceptionHandler(NullPointerException.class)
public Object nullPointerexceptionAdvice(NullPointerException e) {
HashMap<String, Object> result = new HashMap<>();
result.put("success", -1);
result.put("message", "空指針異常:" + e.getMessage());
result.put("data", null);
return result;
}
}
當有多個異常通知時,匹配順序爲當前類及其子類向上依次匹配,案例演示:
在 UserController 中設置⼀個空指針異常,實現代碼如下:
@RestController
@RequestMapping("/u")
public class UserController {
@RequestMapping("/index")
public String index() {
Object obj = null;
int i = obj.hashCode();
return "Hello,User Index.";
}
}
以上程序的執⾏結果如下:
此時若出現異常就不會報錯了,代碼會繼續執行,但是會把自定義的異常信息返回給前端!
統一完數據返回格式後:
package com.example.demo.common;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 異常類的統一處理
*/
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
public Object exceptionAdvice(Exception e) {
return AjaxResult.fail(-1, e.getMessage());
}
}
統一異常處理不用配置路徑,是攔截整個項目中的所有異常。
三、統一數據返回格式
3.1 爲什麼需要統一數據返回格式?
統⼀數據返回格式的優點有很多,比如以下幾個:
- ⽅便前端程序員更好的接收和解析後端數據接⼝返回的數據。
- 降低前端程序員和後端程序員的溝通成本,按照某個格式實現就⾏了,因爲所有接⼝都是這樣返回的。
- 有利於項⽬統⼀數據的維護和修改。
- 有利於後端技術部⻔的統⼀規範的標準制定,不會出現稀奇古怪的返回內容。
3.2 統一數據返回格式的實現
統⼀的數據返回格式可以使用 @ControllerAdvice + ResponseBodyAdvice 接口 的方式實現,具體實現代碼如下:
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyA
dvice;
import java.util.HashMap;
/**
* 統一返回數據的處理
*/
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
/**
* 內容是否需要重寫(通過此⽅法可以選擇性部分控制器和⽅法進⾏重寫)
* 返回 true 表示重寫
*/
@Override
public boolean supports(MethodParameter returnType, Class converterTyp
e) {
return true;
}
/**
* ⽅法返回之前調⽤此⽅法
*/
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class selectedConverterType, ServerHttpR
equest request,
ServerHttpResponse response) {
// 構造統⼀返回對象
HashMap<String, Object> result = new HashMap<>();
result.put("state", 1);
result.put("msg", "");
result.put("data", body);
return result;
}
}
統一處理後,此時所有返回的都是 json 格式的數據了。
若方法的返回類型爲 String,統一數據返回格式封裝後,返回會報錯!?
轉換器的問題,解決方案:
實際開發中這種統一數據返回格式的方式並不常用。因爲它會將所有返回都再次進行封裝,過於霸道了 ~
而通常我們會寫一個統一封裝的類,讓程序猿在返回時統一返回這個類 (軟性約束),例如:
package com.example.demo.common;
import java.util.HashMap;
/**
* 自定義的統一返回對象
*/
public class AjaxResult {
/**
* 業務執行成功時進行返回的方法
*
* @param data
* @return
*/
public static HashMap<String, Object> success(Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "");
result.put("data", data);
return result;
}
/**
* 業務執行成功時進行返回的方法
*
* @param data
* @return
*/
public static HashMap<String, Object> success(String msg, Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", msg);
result.put("data", data);
return result;
}
/**
* 業務執行失敗返回的數據格式
*
* @param code
* @param msg
* @return
*/
public static HashMap<String, Object> fail(int code, String msg) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
result.put("data", "");
return result;
}
/**
* 業務執行失敗返回的數據格式
*
* @param code
* @param msg
* @return
*/
public static HashMap<String, Object> fail(int code, String msg, Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
result.put("data", data);
return result;
}
}
同時搭配統一數據返回格式:
package com.example.demo.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.HashMap;
/**
* 統一數據返回封裝
*/
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof HashMap) { // 本身已經是封裝好的對象
return body;
}
if (body instanceof String) { // 返回類型是 String(特殊)
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(AjaxResult.success(body));
}
return AjaxResult.success(body);
}
}
3.3 @ControllerAdvice 源碼分析(瞭解)
通過對 @ControllerAdvice 源碼的分析我們可以知道上⾯統⼀異常和統⼀數據返回的執⾏流程,我們先從 @ControllerAdvice 的源碼看起,點擊 @ControllerAdvice 實現源碼如下:
從上述源碼可以看出 @ControllerAdvice 派⽣於 @Component 組件,⽽所有組件初始化都會調用 InitializingBean 接⼝。
所以接下來我們來看 InitializingBean 有哪些實現類?在查詢的過程中我們發現了,其中 Spring MVC 中的實現⼦類是 RequestMappingHandlerAdapter,它⾥⾯有⼀個⽅法 afterPropertiesSet() ⽅法,表示所有的參數設置完成之後執⾏的⽅法,如下圖所示:
⽽這個⽅法中有⼀個 initControllerAdviceCache ⽅法,查詢此⽅法的源碼如下:
我們發現這個⽅法在執⾏是會查找使⽤所有的 @ControllerAdvice 類,這些類會被容器中,但發⽣某個事件時,調⽤相應的 Advice ⽅法,⽐如返回數據前調⽤統⼀數據封裝,⽐如發⽣異常是調⽤異常的 Advice ⽅法實現。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://blog.csdn.net/yyhgo_/article/details/128755308