解析Spring Mvc Long類型精度丟失問題
背景
在使用Spring Boot Mvc的項(xiàng)目中,使用Long類型作為id的類型,但是當(dāng)前端使用Number類型接收Long類型數(shù)據(jù)時(shí),由于前端精度問題,會導(dǎo)致Long類型數(shù)據(jù)轉(zhuǎn)換為Number類型時(shí)的后兩位變?yōu)?
Spring Boot Controller
以下代碼提供一個(gè)Controller,返回一個(gè)Dto, Dto的id是Long類型的,其中id的返回?cái)?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)實(shí)際上id返回的結(jié)果是1234567890102349000,最后幾位都變成了00, 這是因?yàn)?,javascript的Number類型最大長度是17位,而后端返回的Long類型有19位,導(dǎo)致js的Number不能解析。

方案
既然不能使用js的Number接收,那么前端如何Long類型的數(shù)據(jù)呢,答案是js使用string類型接收
方案一 @JsonSerialize 注解
修改Dto的id字段,使用@JsonSerialize注解指定類型為string。
這個(gè)方案有一個(gè)問題,就是需要程序員明確指定@JsonSerialize, 在實(shí)際的使用過程中,程序員會很少注意到Long類型的問題,只有和前端聯(lián)調(diào)的時(shí)候發(fā)現(xiàn)不對。
@Data
public static class GetLongValueDto{
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
}

方案二 全局處理器
添加Configuration, 處理 HttpMessageConverter
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
/**
* 序列化json時(shí),將所有的long變成string
* 因?yàn)閖s中得數(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集成
上面只是解決了傳輸時(shí)的long類型轉(zhuǎn)string,但是當(dāng)集成了swagger時(shí),swagger文檔描述的類型仍然是number類型的,這樣在根據(jù)swagger文檔生成時(shí),會出現(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)文章
詳解SpringBoot是如何整合SpringDataRedis的?
今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識,文章圍繞著SpringBoot是如何整合SpringDataRedis展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
SpringMVC運(yùn)行時(shí)出現(xiàn)404錯誤的解決辦法匯總(基本包含所有錯誤可能)
初學(xué)SpringMVC基本都會碰到404問題(確實(shí)也困擾了我好長時(shí)間),但出現(xiàn)404問題的原因有很多,如果確認(rèn)路徑,代碼沒問題,并且服務(wù)器可以正常啟動,依然出現(xiàn)404問題的話,就根據(jù)本篇步驟逐一排查,需要的朋友可以參考下2024-04-04
Java基礎(chǔ)之SpringBoot整合knife4j
Swagger現(xiàn)在已經(jīng)成了最流行的接口文檔生成與管理工具,但是你是否在用的時(shí)候也在吐槽,它是真的不好看,接口測試的json數(shù)據(jù)沒法格式化,測試地址如果更改了還要去改配置,接口測試時(shí)增加token驗(yàn)證是真的麻煩…針對Swagger的種種缺點(diǎn),Knife4j就呼之欲出了.需要的朋友可以參考下2021-05-05
springboot多數(shù)據(jù)源使用@Qualifier自動注入無效的解決
這篇文章主要介紹了springboot多數(shù)據(jù)源使用@Qualifier自動注入無效的解決,具有很好的參考價(jià)值,希望對大家有所幫助。也希望大家多多支持腳本之家2021-11-11
Spring?Boot項(xiàng)目完美大一統(tǒng)(結(jié)果異常日志統(tǒng)一)
這篇文章主要為大家介紹了Spring?Boot項(xiàng)目完美大一統(tǒng)(結(jié)果異常日志統(tǒng)一)的實(shí)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
詳解Java線程池如何統(tǒng)計(jì)線程空閑時(shí)間
這篇文章主要和大家分享一個(gè)面試題:Java線程池是怎么統(tǒng)計(jì)線程空閑時(shí)間?文中的示例代碼講解詳細(xì),對我們掌握J(rèn)ava有一定幫助,需要的可以參考一下2022-11-11

