前言:
大家好,我是良辰丫,在上一篇文章中我們已經(jīng)學(xué)習(xí)了一些統(tǒng)一功能處理的相關(guān)知識(shí),今天我們繼續(xù)深入學(xué)習(xí)這些知識(shí),主要學(xué)習(xí)統(tǒng)一異常處理,統(tǒng)一的返回格式,@ControllerAdvice簡(jiǎn)單分析.??????
??個(gè)人主頁(yè):良辰針不戳
??所屬專欄:javaEE進(jìn)階篇之框架學(xué)習(xí)
??勵(lì)志語(yǔ)句:生活也許會(huì)讓我們遍體鱗傷,但最終這些傷口會(huì)成為我們一輩子的財(cái)富。
??期待大家三連,關(guān)注,點(diǎn)贊,收藏。
??作者能力有限,可能也會(huì)出錯(cuò),歡迎大家指正。
??愿與君為伴,共探Java汪洋大海。
1. 統(tǒng)一異常處理
1.1 制造一個(gè)算術(shù)異常
我們首先來(lái)制造一個(gè)算術(shù)異常,除數(shù)不能為0.
@RequestMapping("/login")
public String login(){
int num = 10/0;
return "執(zhí)行了login";
}
我們先不用處理異常,觀察我們的瀏覽器效果.
1.2 處理異常
- 創(chuàng)建一個(gè)類(lèi),在類(lèi)上標(biāo)識(shí)注解@ControllerAdvice,這個(gè)注解可以感知異常.
- 通過(guò)注解 @ExceptionHandler來(lái)訂閱異常
package com.example.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;
@ResponseBody
@ControllerAdvice
public class ExDeal {
@ExceptionHandler(ArithmeticException.class)
public HashMap<String, String> arithmeticException(ArithmeticException e) {
HashMap<String, String> result = new HashMap<>();
result.put("code", "-1");
result.put("msg", "算術(shù)異常異常:" + e.getMessage()); // 錯(cuò)誤碼的描述信息
result.put("data", "除數(shù)不能為0");
return result;
}
}
Exception包含所有的異常,參數(shù)寫(xiě)成Exception也可以,注意是方法的參數(shù).
接下來(lái)我們觀察瀏覽器效果.
2. 統(tǒng)一的返回格式
注意 : 我們?cè)谏弦黄恼聦W(xué)習(xí)了攔截器,我們制定了一些攔截規(guī)則,我們一會(huì)要舉一個(gè)例子進(jìn)行測(cè)試我們的統(tǒng)一的返回格式,因此我們可以先把攔截器的代碼注釋掉.
2.1 為什么需要統(tǒng)一返回格式呢?
- ?便前端程序員更好的接收和解析后端數(shù)據(jù)接?返回的數(shù)據(jù)。
- 降低前端程序員和后端程序員的溝通成本,按照某個(gè)格式實(shí)現(xiàn)就?了,因?yàn)樗薪?都是這樣返回的。
- 有利于項(xiàng)?統(tǒng)?數(shù)據(jù)的維護(hù)和修改。
- 有利于后端技術(shù)部?的統(tǒng)?規(guī)范的標(biāo)準(zhǔn)制定,不會(huì)出現(xiàn)稀奇古怪的返回內(nèi)容。
- 也就是前后端做出格式約定,可以極大的方便程序員去處理各種各樣的問(wèn)題,格式不統(tǒng)一會(huì)有格式轉(zhuǎn)換等不便捷的缺點(diǎn),也不利于程序員維護(hù).
2.2 寫(xiě)一個(gè)隨機(jī)返回?cái)?shù)函數(shù)
我們先在user類(lèi)中寫(xiě)一個(gè)隨機(jī)返回?cái)?shù)字代碼,運(yùn)行通過(guò)瀏覽器觀察效果.
@RequestMapping("/num")
public Integer num(){
Random random = new Random();
int num = random.nextInt(1000);
return num;
}
然而后端并不知道我們的格式,因?yàn)槲覀兛赡苁亲址?整型等各種各樣的數(shù)據(jù)類(lèi)型.
2.3 創(chuàng)建一個(gè)類(lèi)并且添加@ControllerAdvice
package com.example.demo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
public class Respons {
}
2.4 實(shí)現(xiàn)ResponseBodyAdvice接口并重寫(xiě)方法
我們要實(shí)現(xiàn)ResponseBodyAdvice接口,并且重寫(xiě)supports方法以及beforeBodyWrite方法(統(tǒng)一對(duì)象急速在此方法中實(shí)現(xiàn)的)
package com.example.demo;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
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.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
@ControllerAdvice
public class Response implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
//默認(rèn)是false,表示開(kāi)關(guān)關(guān)掉,意味著下面的重寫(xiě)效果沒(méi)有用途
// return false;
//返回true的時(shí)候才會(huì)執(zhí)行下面的beforeBodyWrite方法
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
HashMap<String,Object> map = new HashMap<>();
//添加狀態(tài)碼,200表示成功
map.put("code","200");
//錯(cuò)誤的描述信息
map.put("msg",null);
//數(shù)據(jù)body
map.put("data",body);
return map;
}
}
然后我們觀察統(tǒng)一格式后的效果
2.5 返回格式處理String類(lèi)型出現(xiàn)問(wèn)題
我們?cè)趌ogin中返回的是一個(gè)字符串,當(dāng)我們通過(guò)瀏覽器訪問(wèn)我們的login頁(yè)面的時(shí)候會(huì)發(fā)現(xiàn)有一定的問(wèn)題,錯(cuò)誤是不能進(jìn)行類(lèi)型轉(zhuǎn)化,這是為什么呢?
- String既不屬于基本數(shù)據(jù)類(lèi)型,又不屬于對(duì)象.
- String使用的是自己的格式化工具,我們需要使用jackon進(jìn)行類(lèi)型轉(zhuǎn)換.
- 因此如果是String需要特殊處理,我們先要通過(guò)屬性注入把ObjectMapper注入進(jìn)來(lái),因?yàn)樘幚鞸tring需要這個(gè)方法.
package com.example.demo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
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.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
@ControllerAdvice
public class Response implements ResponseBodyAdvice {
@Autowired
private ObjectMapper objectMapper;
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
//默認(rèn)是false,表示開(kāi)關(guān)關(guān)掉,意味著下面的重寫(xiě)效果沒(méi)有用途
// return false;
//返回true的時(shí)候才會(huì)執(zhí)行下面的beforeBodyWrite方法
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
HashMap<String,Object> map = new HashMap<>();
//添加狀態(tài)碼,200表示成功
map.put("code","200");
//錯(cuò)誤的描述信息
map.put("msg",null);
//數(shù)據(jù)body
map.put("data",body);
if (body instanceof String) {
// 需要特殊處理,因?yàn)?String 在轉(zhuǎn)換的時(shí)候會(huì)報(bào)錯(cuò)
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return map;
}
}
接下來(lái)我們?cè)俅斡^察我們的瀏覽器頁(yè)面效果.
3. @ControllerAdvice簡(jiǎn)單分析
- 我們先進(jìn)入 @ControllerAdvice源碼中,我們驚奇的發(fā)現(xiàn)@ControllerAdvice也是來(lái)自于組件@Component.?所有組件初始化都會(huì)調(diào)?InitializingBean 接?。
- 接下來(lái)我們來(lái)看 InitializingBean 有哪些實(shí)現(xiàn)類(lèi)?在資料中我們發(fā)現(xiàn) Spring MVC中的實(shí)現(xiàn)?類(lèi)是 RequestMappingHandlerAdapter,我們找到一個(gè)initControllerAdviceCache方法.
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-565542.html
- 我們發(fā)現(xiàn)這個(gè)?法在執(zhí)?是會(huì)查找使?所有的 @ControllerAdvice 類(lèi),發(fā)?某個(gè)事件時(shí),調(diào)?相應(yīng)的 Advice ?法,?如返回?cái)?shù)據(jù)前調(diào)?統(tǒng)?數(shù)據(jù)封裝,?如發(fā)?異常是調(diào)?異常的Advice ?法實(shí)現(xiàn)。
- 換句話來(lái)說(shuō),就是有各種各樣的Advice來(lái)處理不同的事件,如果出現(xiàn)了異常事件就會(huì)通過(guò)@ControllerAdvice注解調(diào)用異常事件相關(guān)的Advice進(jìn)行檢測(cè)異常(就是定位異常),然后通過(guò)我們的后端代碼處理異常.
后序:
在Spring Boot統(tǒng)一功能處理我們主要學(xué)習(xí)了統(tǒng)一用戶登錄權(quán)限驗(yàn)證,統(tǒng)一數(shù)據(jù)格式返回,統(tǒng)一異常處理,這些都是在我們的SSM項(xiàng)目中非常重要的,我們需要重點(diǎn)去掌握.??????文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-565542.html
到了這里,關(guān)于【Spring Boot統(tǒng)一功能處理】統(tǒng)一異常處理,統(tǒng)一的返回格式,@ControllerAdvice簡(jiǎn)單分析,即將走進(jìn)SSM項(xiàng)目的大門(mén)! ! !的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!