實(shí)現(xiàn) ResponseBodyAdvice
攔截了 接口 的返回?cái)?shù)據(jù)醒陆,對(duì)返回?cái)?shù)據(jù)進(jìn)行封裝,這樣可以保持一個(gè)統(tǒng)一的模板格式給前端裆针,易于前端處理刨摩,同時(shí),簡化后端每個(gè)接口都需要手動(dòng)構(gòu)建返回格式的維護(hù)等
自定義返回模板
ResponseTemplate
ResponseTemplate 示例
Hello World
Hello World 接口
此時(shí)請(qǐng)求 hello接口世吨,會(huì)報(bào)ResponseTemplate不能轉(zhuǎn)為string的異常
解決
重寫WebMvcConfigurerAdapter
重寫WebMvcConfigurerAdapter澡刹,覆蓋了原有的HttpMessageConverters,此處采用:com.alibaba.fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
新問題
解決了轉(zhuǎn)換異常耘婚,又遇到中文亂碼
再解決
配置文件添加
spring:
http:
encoding:
charset: UTF-8
force: true
enabled: true
messages:
encoding: UTF-8
banner:
charset: UTF-8
效果
接口返回?cái)?shù)據(jù)