SpringBoot統(tǒng)一功能處理示例詳解(攔截器)
1.用戶登錄權(quán)限校驗
1.1自定義攔截器
寫一個類去實現(xiàn)HandlerInterceptor接口表示當前類是一個攔截器,再重寫HandlerInterceptor接口中的方法,preHandle為在方法執(zhí)行前攔截,postHandle為方法執(zhí)行中攔截,afterCompletion為方法執(zhí)行中攔截.需要在什么時候攔截就重寫什么方法
@Component public class LoginIntercepetor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 判斷用戶登錄 HttpSession session = request.getSession(false); if(session!=null && session.getAttribute(ApplicationVariable.SESSION_USERINFO_KEY)!=null){ // 用戶已經(jīng)登錄 return true; } // 當代碼執(zhí)行到此處說明用戶未登錄 response.sendRedirect("/login.html"); return false; } }
1.2.配置攔截規(guī)則
@Configuration public class MyConfig implements WebMvcConfigurer { @Autowired private LoginInterceptor loginInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor) .addPathPatterns("/**") //攔截所有的URL .excludePathPatterns("/user/login") // 排除 url /user/login 不攔截 .excludePathPatterns("/user/reg") // 排除 url /user/login 不攔截 ; } }
實現(xiàn)WebMvcConfigurer接口,重寫WebMvcConfigurer中的addInterceptors方法,在使用 InterceptorRegistry參數(shù) 配置攔截規(guī)則
攔截器實現(xiàn)原理
統(tǒng)一異常處理
創(chuàng)建異常處理類
@ControllerAdvice @ResponseBody public class MyExceptionAdvice { }
ControllerAdvice注解的作用:1.和Controller注解作用一樣,讓這個類隨著Spring的啟動而啟動. 2.監(jiān)測添加了Controller注解的類的異常
創(chuàng)建異常檢測的類和處理業(yè)務
@ExceptionHandler(NullPointerException.class) public HashMap<String,Object> dpNullPointerException(NullPointerException e){ HashMap<String,Object> result = new HashMap<>(); result.put("code",-1); result.put("msg","空指針: "+e.getMessage()); result.put("data",null); return result; }
使用@ExceptionHandler注解,括號里面寫要捕獲的異常,用HashMap的方式返回數(shù)據(jù)給前端,此處以捕獲空指針異常為例,如果想要捕獲所有的異常,可以使用所有異常的父類Exception
@ExceptionHandler(Exception.class) public HashMap<String,Object> doException(Exception e){ HashMap<String,Object> result = new HashMap<>(); result.put("code",-1); result.put("msg","Exception: "+e.getMessage()); result.put("data",null); return result; }
統(tǒng)一數(shù)據(jù)格式返回(在返回數(shù)據(jù)之前進行數(shù)據(jù)重寫)
@ControllerAdvice public class MyResponseAdvice implements ResponseBodyAdvice { @Autowired ObjectMapper objectMapper; /** * 是否執(zhí)行 beforeBodyWrite 方法,true=執(zhí)行 重寫返回結(jié)果,false=不執(zhí)行 * * @param returnType * @param converterType * @return */ @Override public boolean supports(MethodParameter returnType, Class converterType) { return true; } /** * 在返回數(shù)據(jù)之前進行數(shù)據(jù)重寫 * * @param body 原始返回值 * @param returnType * @param selectedContentType * @param selectedConverterType * @param request * @param response * @return */ @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { //定義一個標準的返回格式 //Hash<String,Object> code,msg,data if(body instanceof HashMap){ return body; } // 重寫返回結(jié)果,讓其返回一個統(tǒng)一的數(shù)據(jù)格式 HashMap<String,Object> result = new HashMap<>(); result.put("code",200); result.put("msg",""); result.put("data",body); if(body instanceof String){ // 返回一個 String 字符串 try { objectMapper.writeValueAsString(result); } catch (JsonProcessingException e) { e.printStackTrace(); } return result; } return result; } }
使用ResponseBodyAdvice接口,重寫supports和beforeBodyWrite方法,這種方式如果原方法返回的是字符串,不進行特殊處理會報錯(執(zhí)行流程:
1.方法返回的是 String
2.統(tǒng)一數(shù)據(jù)返回之前處理 把String 轉(zhuǎn)換成 HashMap
3.將 HashMap 轉(zhuǎn)換成 application/json 字符串給前端(接口)),在第三步的時候會判斷原 body 類型,根據(jù)類型選擇不同的 消息轉(zhuǎn)換器 去轉(zhuǎn)換,如果是String 類型會使用StringHttpMessageConverter進行類型轉(zhuǎn)換,如果非String 類型,會使用 HttpMessageConverter 進行類型轉(zhuǎn)換.但是事實上StringHttpMessageConverter 消息轉(zhuǎn)換器不能把HashMap轉(zhuǎn)換為json格式的字符串,因此會報錯. 我們可以在統(tǒng)一數(shù)據(jù)重寫時,單獨處理String類型,讓其返回一個 String 字符串,而非HashMap
到此這篇關(guān)于SpringBoot統(tǒng)一功能處理(攔截器)的文章就介紹到這了,更多相關(guān)SpringBoot統(tǒng)一功能處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決RestTemplate 請求url中包含百分號 會被轉(zhuǎn)義成25的問題
這篇文章主要介紹了解決RestTemplate 請求url中包含百分號 會被轉(zhuǎn)義成25的問題,具有很好的參考價值,希望對大家有所幫助。2021-10-10java大數(shù)乘法的簡單實現(xiàn) 浮點數(shù)乘法運算
大數(shù)乘法可以進行任意大小和精度的整數(shù)和浮點數(shù)的乘法運算, 精確度很高, 可以用作經(jīng)融等領(lǐng)域的計算,這個是我看了一些資料, 然后自己整理實現(xiàn)的,簡單測試了一下2014-01-01Java快速實現(xiàn)PDF轉(zhuǎn)圖片功能實例代碼
PDFBox是一個開源Java類庫,用于讀取和創(chuàng)建PDF文檔,它支持文本提取、表單處理、文檔加密解密、合并分割、內(nèi)容覆蓋追加、文檔打印和轉(zhuǎn)換等功能,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-09-09