解析Spring Mvc Long类型精度丢失问题
作者:诸葛小亮 发布时间:2021-11-06 12:27:37
背景
在使用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文档中类型描述,避免生成代码器中描述的类型错误
来源:https://www.cnblogs.com/zhaord/p/14857359.html
猜你喜欢
- 前言最常用的对字符串操作的类有三个,分别是String,StringBuilder,StringBuffer,下面将会详细的说说这三个类..
- 先看下效果:两种需求场景:1.广告页3s后跳转到首页2.短信验证码60s倒计时第一种的话,根据需求我们可以知道,我们想要的效果就是3s结束做
- 一、概述在微服务架构中,我们将系统拆分成了很多服务单元,各单元的应用间通过服务注册与订阅的方式互相依赖。由于每个单元都在不同的进程中运行,依
- 树的同构备忘!定义:给定两棵树r1、r2,如果r1可以通过若干次的左子树和右子树互换,使之与r2完全相同,这说明两者同构。举例树的构造树可以
- 首先,良好的编码规范非常重要。在 java 程序中,访问速度、资源紧张等问题的大部分原因,都是代码不规范造成的。单例的使用场景单例模式对于减
- 一、Rxjava使用场景为了模拟实际场景,从wanandroid网站找了二个接口,如下:(对Wanandroid表示感谢!)public i
- 前言ps命令的作用是显示进程信息的。|符号,是个管道符号,表示左右两边两个命令同时执行。grep命令是查找(Global Regular E
- 【SpringBoot】通过Feign调用传递Header中参数如何通过Feign传递Header参数问题描述我们在SpringCloud中
- intellij idea是一款非常优秀的软件开发工具,它拥有这强大的插件体系,可以帮助开发者完成很多重量级的功能。今天,我们来学习一下如何
- 首先我们看看为什么需要对象复制?为什么需要对象复制如上,是我们平时开发中最常见的三层MVC架构模型,编辑操作时Controller层接收到前
- 本文实例为大家分享了C语言自定义扫雷游戏的具体代码,供大家参考,具体内容如下实现过程对于用C语言实现扫雷游戏得实现,可将游戏过程分为两个板块
- List list=new ArrayList()是怎么回事首先明确List是接口,ArrayList是它的实现类以下两种方法都可以,但是不
- 应用场景假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费如果仓库中没有产品,则生产者将产品放入仓库,否
- 1、动态SQL片段通过SQL片段达到代码复用 <!-- 动态条件分页查询 --> <sql i
- 整理文档,java 动态增加定时任务示例,直接上代码。import org.apache.tools.ant.util.DateUtils;
- 目录一,功能二,工具三、效果图:四、数据库设计五、JAVA层次分析六、主要Java代码分析一,功能管理员登录图书借阅信息管理图书信息管理管理
- 参考:How to catch an Exception from a threadIs there a way to make Runna
- Mybatis typeAlias配置1.定义别名<typeAliases> <ty
- springboot微服务内置了tomcat,在工程目录下执行:mvn clean package,可以将项目打成jar,通过java -j
- 前言之前采取项目中嵌套html页面,实现基本的登录校验、权限校验、登出操作、记住我等功能试下。但是,现在的开发基本都是前后分离样式,后端并不