解析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()@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; }}前端調(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>
運行結(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
@Configurationpublic 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)
@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') //文檔標(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了
以上就是Spring Mvc Long類型精度丟失的詳細內(nèi)容,更多關(guān)于Spring Mvc Long類型的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP.NET MVC實現(xiàn)下拉框多選2. JSP中param動作的實例詳解3. Jsp servlet驗證碼工具類分享4. .NET中的MassTransit分布式應(yīng)用框架詳解5. 解決request.getParameter取值后的if判斷為NULL的問題6. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別7. .Net反向代理組件Yarp用法詳解8. ASP.NET MVC增加一條記錄同時添加N條集合屬性所對應(yīng)的個體9. 刪除docker里建立容器的操作方法10. 詳解如何使用Net將HTML簡歷導(dǎo)出為PDF格式
