Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Long integer Long returns to the front end. What if the precision of js is lost?

Shulou Source: shulou.com Published: 2022-06-03 03:18:13 09月23日 Update

When the front-end interface is docked, if the id or other fields in the background use the long integer Long, it is easy to lose the precision of js. When called by interface tools, id returns are often correct, but once on the page, js will be suffixed with 000.

The front end says there is a problem with the returned value, F12 take a look! The back end says no problem, Postman look!

This is a problem supported by js, and the solution to this problem is obviously to return a string.

How to achieve it, you can directly change the id of vo object to String type, but it will bring the inconvenience of copyProperties, so I have seen many people achieve it by adding virtual fields. Here's an overall solution: (Need a little understanding of Spring's message serialization principles, such as MappingJackson2 HttpMessage Converter is what)

MainConfig (usually the main config class, annotated with @Configuration, used to import some basic configuration) added MessageConvert rewrite extendMessageConverters:

@Overridepublic void extendMessageConverters(List converter : converters) { if (converter instanceof MappingJackson2HttpMessageConverter) { jacksonConverter = (MappingJackson2HttpMessageConverter) converter; } } if (jacksonConverter != null) { jacksonConverter.setObjectMapper(new CustomObjectMapper()); converters.add(jacksonConverter); }}CustomObjectMapper implementation: public class CustomObjectMapper extends ObjectMapper {public CustomObjectMapper() { super(); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(Long.class, ToStringSerializer.instance); simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); registerModule(simpleModule);}}

So, when the interface returns, all the long fields are treated as strings and are automatically quoted.

Tags: Problem field interface front end character string precision inconvenience method principle background suffix foundation object tool sequence quotation mark whole scheme time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Tech Info Microsoft Docker MariaDB