您的位置:首頁/技術文章
文章詳情頁

解析Spring Mvc Long類型精度丟失問題

【字号: 作者:豬豬瀏覽:2日期:2023-07-12 13:06:48
目錄背景Spring Boot Controller前端調用方案方案一 @JsonSerialize 注解方案二 全局處理器與swagger集成總結背景

在使用Spring Boot Mvc的項目中,使用Long類型作為id的類型,但是當前端使用Number類型接收Long類型數據時,由于前端精度問題,會導致Long類型數據轉換為Number類型時的后兩位變為0

Spring Boot Controller

以下代碼提供一個Controller,返回一個Dto, Dto的id是Long類型的,其中id的返回數據是1234567890102349123@CrossOrigin 注解表示可以跨域訪問

@RestController()@RequestMappingpublic 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; }}前端調用

現在使用jquery調用后端地址,模擬前端調用

<!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>

運行結果

通過輸出結果和查看網絡的內容,發現實際上id返回的結果是1234567890102349000,最后幾位都變成了00, 這是因為,javascript的Number類型最大長度是17位,而后端返回的Long類型有19位,導致js的Number不能解析。

解析Spring Mvc Long類型精度丟失問題

方案

既然不能使用js的Number接收,那么前端如何Long類型的數據呢,答案是js使用string類型接收

方案一 @JsonSerialize 注解

修改Dto的id字段,使用@JsonSerialize注解指定類型為string。這個方案有一個問題,就是需要程序員明確指定@JsonSerialize, 在實際的使用過程中,程序員會很少注意到Long類型的問題,只有和前端聯調的時候發現不對。

@Data public static class GetLongValueDto{@JsonSerialize(using= ToStringSerializer.class)private Long id; }

解析Spring Mvc Long類型精度丟失問題

方案二 全局處理器

添加Configuration, 處理 HttpMessageConverter

@Configurationpublic class WebConfiguration implements WebMvcConfigurer { /** * 序列化json時,將所有的long變成string * 因為js中得數字類型不能包含所有的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; }

解析Spring Mvc Long類型精度丟失問題

發現沒有@JsonSerialize注解的信息,前端接收到的數據,也是string類型了。

與swagger集成

上面只是解決了傳輸時的long類型轉string,但是當集成了swagger時,swagger文檔描述的類型仍然是number類型的,這樣在根據swagger文檔生成時,會出現類型不匹配的問題

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>

查看文檔, 發現 GetLongValueDto 描述的id類型是 integer($int64)

解析Spring Mvc Long類型精度丟失問題

swagger long類型描述為string

需要修改swagger的配置, 修改 Docket 的配置

.directModelSubstitute(Long.class, String.class).directModelSubstitute(long.class, String.class)

@Configurationpublic 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') //文檔標題.description('description')//接口概述.version('1.0') //版本號.termsOfServiceUrl(String.format('url'))//服務的域名//.license('LICENSE')//證書//.licenseUrl('http://www.guangxu.com')//證書的url.build(); }}

查看swagger文檔 , 可以看到 文檔中類型已經是 string了

解析Spring Mvc Long類型精度丟失問題

總結 long類型傳輸到前端的兩種方案:注解、修改HttpMessageConverter 使用directModelSubstitute解決swagger文檔中類型描述,避免生成代碼器中描述的類型錯誤

以上就是Spring Mvc Long類型精度丟失的詳細內容,更多關于Spring Mvc Long類型的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
国产综合久久一区二区三区