SpringBoot統(tǒng)一功能處理示例詳解(攔截器)
1.用戶登錄權(quán)限校驗(yàn)
1.1自定義攔截器
寫一個(gè)類去實(shí)現(xiàn)HandlerInterceptor接口表示當(dāng)前類是一個(gè)攔截器,再重寫HandlerInterceptor接口中的方法,preHandle為在方法執(zhí)行前攔截,postHandle為方法執(zhí)行中攔截,afterCompletion為方法執(zhí)行中攔截.需要在什么時(shí)候攔截就重寫什么方法
@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;
}
// 當(dāng)代碼執(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 不攔截
;
}
}實(shí)現(xiàn)WebMvcConfigurer接口,重寫WebMvcConfigurer中的addInterceptors方法,在使用 InterceptorRegistry參數(shù) 配置攔截規(guī)則
攔截器實(shí)現(xiàn)原理

統(tǒng)一異常處理
創(chuàng)建異常處理類
@ControllerAdvice
@ResponseBody
public class MyExceptionAdvice {
}ControllerAdvice注解的作用:1.和Controller注解作用一樣,讓這個(gè)類隨著Spring的啟動(dòng)而啟動(dòng). 2.監(jiān)測(cè)添加了Controller注解的類的異常
創(chuàng)建異常檢測(cè)的類和處理業(yè)務(wù)
@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注解,括號(hào)里面寫要捕獲的異常,用HashMap的方式返回?cái)?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ù)格式返回(在返回?cái)?shù)據(jù)之前進(jìn)行數(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;
}
/**
* 在返回?cái)?shù)據(jù)之前進(jìn)行數(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) {
//定義一個(gè)標(biāo)準(zhǔn)的返回格式
//Hash<String,Object> code,msg,data
if(body instanceof HashMap){
return body;
}
// 重寫返回結(jié)果,讓其返回一個(gè)統(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){
// 返回一個(gè) String 字符串
try {
objectMapper.writeValueAsString(result);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
return result;
}
}使用ResponseBodyAdvice接口,重寫supports和beforeBodyWrite方法,這種方式如果原方法返回的是字符串,不進(jìn)行特殊處理會(huì)報(bào)錯(cuò)(執(zhí)行流程:
1.方法返回的是 String
2.統(tǒng)一數(shù)據(jù)返回之前處理 把String 轉(zhuǎn)換成 HashMap
3.將 HashMap 轉(zhuǎn)換成 application/json 字符串給前端(接口)),在第三步的時(shí)候會(huì)判斷原 body 類型,根據(jù)類型選擇不同的 消息轉(zhuǎn)換器 去轉(zhuǎn)換,如果是String 類型會(huì)使用StringHttpMessageConverter進(jìn)行類型轉(zhuǎn)換,如果非String 類型,會(huì)使用 HttpMessageConverter 進(jìn)行類型轉(zhuǎn)換.但是事實(shí)上StringHttpMessageConverter 消息轉(zhuǎn)換器不能把HashMap轉(zhuǎn)換為json格式的字符串,因此會(huì)報(bào)錯(cuò). 我們可以在統(tǒng)一數(shù)據(jù)重寫時(shí),單獨(dú)處理String類型,讓其返回一個(gè) String 字符串,而非HashMap
到此這篇關(guān)于SpringBoot統(tǒng)一功能處理(攔截器)的文章就介紹到這了,更多相關(guān)SpringBoot統(tǒng)一功能處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決RestTemplate 請(qǐng)求url中包含百分號(hào) 會(huì)被轉(zhuǎn)義成25的問題
這篇文章主要介紹了解決RestTemplate 請(qǐng)求url中包含百分號(hào) 會(huì)被轉(zhuǎn)義成25的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2021-10-10
java大數(shù)乘法的簡(jiǎn)單實(shí)現(xiàn) 浮點(diǎn)數(shù)乘法運(yùn)算
大數(shù)乘法可以進(jìn)行任意大小和精度的整數(shù)和浮點(diǎn)數(shù)的乘法運(yùn)算, 精確度很高, 可以用作經(jīng)融等領(lǐng)域的計(jì)算,這個(gè)是我看了一些資料, 然后自己整理實(shí)現(xiàn)的,簡(jiǎn)單測(cè)試了一下2014-01-01
Java快速實(shí)現(xiàn)PDF轉(zhuǎn)圖片功能實(shí)例代碼
PDFBox是一個(gè)開源Java類庫(kù),用于讀取和創(chuàng)建PDF文檔,它支持文本提取、表單處理、文檔加密解密、合并分割、內(nèi)容覆蓋追加、文檔打印和轉(zhuǎn)換等功能,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-09-09
java應(yīng)用開發(fā)之JVM運(yùn)行時(shí)內(nèi)存分析
這篇文章主要介紹了java應(yīng)用開發(fā)之JVM運(yùn)行時(shí)內(nèi)存,文中附含圖文示例內(nèi)容分析非常簡(jiǎn)要,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-09-09
Spring Boot中使用Redis做緩存的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Spring Boot中使用Redis做緩存的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-06-06

