解析Spring Mvc Long類型精度丟失問題
背景
在使用Spring Boot Mvc的項目中,使用Long類型作為id的類型,但是當(dāng)前端使用Number類型接收Long類型數(shù)據(jù)時,由于前端精度問題,會導(dǎo)致Long類型數(shù)據(jù)轉(zhuǎn)換為Number類型時的后兩位變?yōu)?
Spring Boot Controller
以下代碼提供一個Controller,返回一個Dto, Dto的id是Long類型的,其中id的返回數(shù)據(jù)是1234567890102349123
@CrossOrigin
注解表示可以跨域訪問
@RestController() @RequestMapping public class LongDemoController { @GetMapping("getLongValue") @CrossOrigin(origins = "*") public GetLongValueDto getLongValue(){ GetLongValueDto result = new GetLongValueDto(); result.setId(1234567890102349123L); return result; } @Data public static class GetLongValueDto{ private Long id; } }
前端調(diào)用
現(xiàn)在使用jquery調(diào)用后端地址,模擬前端調(diào)用
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>spring boot mvc long</title> </head> <body> <p>Long:<span id='resId'></span></p> <p>Id類型:<span id='idType'></span></p> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ console.log('init'); $.ajax({url:"http://localhost:8080/getLongValue"}) .then(res=>{ console.log({ 'getLongValue':res }); $('#resId').text(res.id); $('#idType').text(typeof res.id); }) }); </script> </body> </html>
運(yùn)行結(jié)果
通過輸出結(jié)果和查看網(wǎng)絡(luò)的內(nèi)容,發(fā)現(xiàn)實際上id返回的結(jié)果是1234567890102349000
,最后幾位都變成了00
, 這是因為,javascript的Number類型最大長度是17位,而后端返回的Long類型有19位,導(dǎo)致js的Number不能解析。
方案
既然不能使用js的Number接收,那么前端如何Long類型的數(shù)據(jù)呢,答案是js使用string類型接收
方案一 @JsonSerialize 注解
修改Dto的id字段,使用@JsonSerialize
注解指定類型為string。
這個方案有一個問題,就是需要程序員明確指定@JsonSerialize
, 在實際的使用過程中,程序員會很少注意到Long類型的問題,只有和前端聯(lián)調(diào)的時候發(fā)現(xiàn)不對。
@Data public static class GetLongValueDto{ @JsonSerialize(using= ToStringSerializer.class) private Long id; }
方案二 全局處理器
添加Configuration, 處理 HttpMessageConverter
@Configuration public class WebConfiguration implements WebMvcConfigurer { /** * 序列化json時,將所有的long變成string * 因為js中得數(shù)字類型不能包含所有的java long值 */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); SimpleModule simpleModule=new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule(simpleModule); jackson2HttpMessageConverter.setObjectMapper(objectMapper); converters.add(0,jackson2HttpMessageConverter); } }
@Data public static class GetLongValueDto{ private Long id; }
發(fā)現(xiàn)沒有@JsonSerialize
注解的信息,前端接收到的數(shù)據(jù),也是string類型了。
與swagger集成
上面只是解決了傳輸時的long類型轉(zhuǎn)string,但是當(dāng)集成了swagger時,swagger文檔描述的類型仍然是number類型的,這樣在根據(jù)swagger文檔生成時,會出現(xiàn)類型不匹配的問題
swagger 文檔集成
pom或gradle
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
查看文檔, 發(fā)現(xiàn) GetLongValueDto 描述的id類型是 integer($int64)
swagger long類型描述為string
需要修改swagger的配置, 修改 Docket
的配置
.directModelSubstitute(Long.class, String.class) .directModelSubstitute(long.class, String.class)
@Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any())//api的配置路徑 .paths(PathSelectors.any())//掃描路徑選擇 .build() .directModelSubstitute(Long.class, String.class) .directModelSubstitute(long.class, String.class) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("title") //文檔標(biāo)題 .description("description")//接口概述 .version("1.0") //版本號 .termsOfServiceUrl(String.format("url"))//服務(wù)的域名 //.license("LICENSE")//證書 //.licenseUrl("http://www.guangxu.com")//證書的url .build(); } }
查看swagger文檔 , 可以看到 文檔中類型已經(jīng)是 string了
總結(jié)
- long類型傳輸?shù)角岸说膬煞N方案:注解、修改
HttpMessageConverter
- 使用
directModelSubstitute
解決swagger文檔中類型描述,避免生成代碼器中描述的類型錯誤
以上就是Spring Mvc Long類型精度丟失的詳細(xì)內(nèi)容,更多關(guān)于Spring Mvc Long類型的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java通過數(shù)據(jù)庫表生成實體類詳細(xì)過程
這篇文章主要介紹了Java通過數(shù)據(jù)庫表生成實體類,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02關(guān)于springboot忽略接口,參數(shù)注解的使用ApiIgnore
這篇文章主要介紹了關(guān)于springboot忽略接口,參數(shù)注解的使用ApiIgnore,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07詳解在idea 中使用Mybatis Generator逆向工程生成代碼
這篇文章主要介紹了在idea 中使用Mybatis Generator逆向工程生成代碼,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12Javaweb應(yīng)用使用限流處理大量的并發(fā)請求詳解
這篇文章主要介紹了Javaweb應(yīng)用使用限流處理大量的并發(fā)請求詳解,還是挺不錯的,這里分享給大家,供需要的朋友參考。2017-11-11springboot多模塊多環(huán)境配置文件問題(動態(tài)配置生產(chǎn)和開發(fā)環(huán)境)
這篇文章主要介紹了springboot多模塊多環(huán)境配置文件問題(動態(tài)配置生產(chǎn)和開發(fā)環(huán)境),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04