SpringBoot統(tǒng)一處理功能實現(xiàn)的全過程
在處理網(wǎng)絡請求時,有一部分功能是需要抽出來統(tǒng)一處理的,與業(yè)務隔開。
登錄校驗
可以利用spring mvc的攔截器Interceptor,實現(xiàn)HandlerInterceptor接口即可。實現(xiàn)該接口后,會在把請求發(fā)給Controller之前進行攔截處理。
攔截器的實現(xiàn)分為以下兩個步驟:
- 創(chuàng)建?定義攔截器,實現(xiàn) HandlerInterceptor 接?的 preHandle(執(zhí)?具體?法之前的預處理)?法。
- 將?定義攔截器加? WebMvcConfigurer 的 addInterceptors ?法中。
我們使用session來作為登錄校驗的例子,實現(xiàn)如下:
package com.demo; 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 { /** * 為 false 則不能繼續(xù)往下執(zhí)行;為 true 則可以。 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 判斷session的信息是否合法 HttpSession session = request.getSession(false); if (session != null && session.getAttribute("userinfo") != null) { return true; } log.error("當前用戶沒有訪問權限"); response.setStatus(401); return false; } }
將寫好的?定義攔截器通過WebMvcConfigurer注冊到容器中,使得攔截器生效,具體實現(xiàn)代碼如下:
package com.demo; 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 } }
如果不注入對象的話,addInterceptor() 的參數(shù)也可以直接 new 一個對象:
@Configuration // 一定不要忘記 public class MyConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") // 攔截所有請求 .excludePathPatterns("/user/login"); // 排除不攔截的 url } }
原理
所有的 Controller 執(zhí)?都會通過spring mvc的調度器 DispatcherServlet 來實現(xiàn),所有?法都會執(zhí)? 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 { // ... 忽略不重要的代碼 // 調?預處理 if (!mappedHandler.applyPreHandle(processedRequest, respon se)) { return; } // 執(zhí)? Controller 中的業(yè)務 mv = ha.handle(processedRequest, response, mappedHandler.g etHandler()); // ... 忽略不重要的代碼 } 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); } } }
從上述源碼可以看出在開始執(zhí)? Controller 之前,會先調? 預處理?法 applyPreHandle,? applyPreHandle ?法的實現(xiàn)源碼如下:
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; }
異常處理
請求時的異常處理也是比較常見的統(tǒng)一處理的對象。
統(tǒng)?異常處理使?的是 @ControllerAdvice + @ExceptionHandler 來實現(xiàn)的,@ControllerAdvice 表示控制器通知類,@ExceptionHandler 是異常處理器,兩個結合表示當出現(xiàn)異常的時候執(zhí)?某個通知,也就是執(zhí)?某個?法事件,具體實現(xiàn)代碼如下:
package com.demo; 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; /** * 統(tǒng)一處理異常 * 一般都需要自定義一個異常對象,這里為了簡單說明只用一個map對象來說明 */ @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; } }
此時若出現(xiàn)異常就不會報錯了,代碼會繼續(xù)執(zhí)行,但是會把自定義的異常信息返回給前端!
原理
@ControllerAdvice是spring的aop對于Controller進行切面所有屬性的,包括切入點和需要織入的切面邏輯,配合@ExceptionHandler來捕獲Controller中拋出的指定類型的異常,從而達到不同類型的異常區(qū)別處理的目的。
返回數(shù)據(jù)結構
統(tǒng)?的返回數(shù)據(jù)結構可以使用 @ControllerAdvice + ResponseBodyAdvice接口 的方式實現(xiàn),具體實現(xiàn)代碼如下:
package com.demo; 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; /** * 統(tǒng)一返回數(shù)據(jù)的處理 */ @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) { // 構造統(tǒng)?返回對象 HashMap<String, Object> result = new HashMap<>(); result.put("state", 1); result.put("msg", ""); result.put("data", body); return result; } }
到此這篇關于SpringBoot統(tǒng)一處理功能實現(xiàn)的全過程的文章就介紹到這了,更多相關SpringBoot統(tǒng)一處理功能內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot+SpringSecurity實現(xiàn)基于真實數(shù)據(jù)的授權認證
Spring Security是一個功能強大且高度可定制的身份驗證和訪問控制框架,Spring Security主要做兩個事情,認證、授權。這篇文章主要介紹了SpringBoot+SpringSecurity實現(xiàn)基于真實數(shù)據(jù)的授權認證,需要的朋友可以參考下2021-05-05JAVA基礎 語句標簽的合法使用,以及{}語句塊到底有什么用?
以前的一個思維誤區(qū),for(){},if(){}之類的用法中,邏輯if()和語句塊{}應該是相互獨立的兩種語法2012-08-08Springboot項目通過redis實現(xiàn)接口的冪等性
這篇文章主要為大家介紹了Springboot項目通過redis實現(xiàn)接口的冪等性,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12