Spring Mvc Long类型 解析Spring Mvc Long类型精度丢失问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring Mvc Long类型 解析Spring Mvc Long类型精度丢失问题

诸葛小亮   2021-06-07 我要评论
想了解解析Spring Mvc Long类型精度丢失问题的相关内容吗,诸葛小亮在本文为您仔细讲解Spring Mvc Long类型的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring,Mvc,Long类型,Spring,Mvc,Long,精度丢失,下面大家一起来学习吧。

背景

在使用Spring Boot Mvc的项目中,使用Long类型作为id的类型,但是当前端使用Number类型接收Long类型数据时,由于前端精度问题,会导致Long类型数据转换为Number类型时的后两位变为0

Spring Boot Controller

以下代码提供一个Controller,返回一个Dto, Dto的id是Long类型的,其中id的返回数据是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;
    }

}

前端调用

现在使用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不能解析。

方案

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

方案一 @JsonSerialize 注解

修改Dto的id字段,使用@JsonSerialize注解指定类型为string。
这个方案有一个问题,就是需要程序员明确指定@JsonSerialize, 在实际的使用过程中,程序员会很少注意到Long类型的问题,只有和前端联调的时候发现不对。

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

方案二 全局处理器

添加Configuration, 处理 HttpMessageConverter

@Configuration
public 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;
    }

发现没有@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)

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") //文档标题
                .description("description")//接口概述
                .version("1.0") //版本号
                .termsOfServiceUrl(String.format("url"))//服务的域名
                //.license("LICENSE")//证书
                //.licenseUrl("http://www.guangxu.com")//证书的url
                .build();
    }

}

查看swagger文档 , 可以看到 文档中类型已经是 string了

总结

  • long类型传输到前端的两种方案:注解、修改HttpMessageConverter
  • 使用directModelSubstitute解决swagger文档中类型描述,避免生成代码器中描述的类型错误

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们