解析Spring Mvc Long類(lèi)型精度丟失問(wèn)題
背景
在使用Spring Boot Mvc的項(xiàng)目中,使用Long類(lèi)型作為id的類(lèi)型,但是當(dāng)前端使用Number類(lèi)型接收Long類(lèi)型數(shù)據(jù)時(shí),由于前端精度問(wèn)題,會(huì)導(dǎo)致Long類(lèi)型數(shù)據(jù)轉(zhuǎn)換為Number類(lèi)型時(shí)的后兩位變?yōu)?
Spring Boot Controller
以下代碼提供一個(gè)Controller,返回一個(gè)Dto, Dto的id是Long類(lèi)型的,其中id的返回?cái)?shù)據(jù)是1234567890102349123
@CrossOrigin
注解表示可以跨域訪(fǎng)問(wèn)
@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類(lèi)型:<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é)果
通過(guò)輸出結(jié)果和查看網(wǎng)絡(luò)的內(nèi)容,發(fā)現(xiàn)實(shí)際上id返回的結(jié)果是1234567890102349000
,最后幾位都變成了00
, 這是因?yàn)?,javascript的Number類(lèi)型最大長(zhǎng)度是17位,而后端返回的Long類(lèi)型有19位,導(dǎo)致js的Number不能解析。
方案
既然不能使用js的Number接收,那么前端如何Long類(lèi)型的數(shù)據(jù)呢,答案是js使用string類(lèi)型接收
方案一 @JsonSerialize 注解
修改Dto的id字段,使用@JsonSerialize
注解指定類(lèi)型為string。
這個(gè)方案有一個(gè)問(wèn)題,就是需要程序員明確指定@JsonSerialize
, 在實(shí)際的使用過(guò)程中,程序員會(huì)很少注意到Long類(lèi)型的問(wèn)題,只有和前端聯(lián)調(diào)的時(shí)候發(fā)現(xiàn)不對(duì)。
@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ù)字類(lèi)型不能包含所有的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)沒(méi)有@JsonSerialize
注解的信息,前端接收到的數(shù)據(jù),也是string類(lèi)型了。
與swagger集成
上面只是解決了傳輸時(shí)的long類(lèi)型轉(zhuǎn)string,但是當(dāng)集成了swagger時(shí),swagger文檔描述的類(lèi)型仍然是number類(lèi)型的,這樣在根據(jù)swagger文檔生成時(shí),會(huì)出現(xiàn)類(lèi)型不匹配的問(wè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類(lèi)型是 integer($int64)
swagger long類(lèi)型描述為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") //版本號(hào) .termsOfServiceUrl(String.format("url"))//服務(wù)的域名 //.license("LICENSE")//證書(shū) //.licenseUrl("http://www.guangxu.com")//證書(shū)的url .build(); } }
查看swagger文檔 , 可以看到 文檔中類(lèi)型已經(jīng)是 string了
總結(jié)
- long類(lèi)型傳輸?shù)角岸说膬煞N方案:注解、修改
HttpMessageConverter
- 使用
directModelSubstitute
解決swagger文檔中類(lèi)型描述,避免生成代碼器中描述的類(lèi)型錯(cuò)誤
以上就是Spring Mvc Long類(lèi)型精度丟失的詳細(xì)內(nèi)容,更多關(guān)于Spring Mvc Long類(lèi)型的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java通過(guò)數(shù)據(jù)庫(kù)表生成實(shí)體類(lèi)詳細(xì)過(guò)程
這篇文章主要介紹了Java通過(guò)數(shù)據(jù)庫(kù)表生成實(shí)體類(lèi),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-02-02關(guān)于springboot忽略接口,參數(shù)注解的使用ApiIgnore
這篇文章主要介紹了關(guān)于springboot忽略接口,參數(shù)注解的使用ApiIgnore,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07詳解在idea 中使用Mybatis Generator逆向工程生成代碼
這篇文章主要介紹了在idea 中使用Mybatis Generator逆向工程生成代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12Javaweb應(yīng)用使用限流處理大量的并發(fā)請(qǐng)求詳解
這篇文章主要介紹了Javaweb應(yīng)用使用限流處理大量的并發(fā)請(qǐng)求詳解,還是挺不錯(cuò)的,這里分享給大家,供需要的朋友參考。2017-11-11springboot多模塊多環(huán)境配置文件問(wèn)題(動(dòng)態(tài)配置生產(chǎn)和開(kāi)發(fā)環(huán)境)
這篇文章主要介紹了springboot多模塊多環(huán)境配置文件問(wèn)題(動(dòng)態(tài)配置生產(chǎn)和開(kāi)發(fā)環(huán)境),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04