Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the long parameters at the back end

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use back-end long parameters". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. description of the problem

Recently in the transformation of the internal management system, found a huge pit, that is, the front-end JS in the acquisition of back-end Long parameters, the loss of precision!

At first, it was normal to simulate interface requests with postman, but there was a problem when using browsers to request them!

Recurrence of the problem:

@ RequestMapping ("/ queryUser") public List queryUser () {List resultList = new ArrayList (); User user = new User (); / / give a long user ID user.setId (123456789012345678L); resultList.add (user); return resultList;}

Open the browser and request the interface. The result is as follows!

Simulate the interface request with postman, and the result is as follows!

At the beginning, I really didn't find this hole, but when I was testing, I found that the ID passed from the front end to the back end was inconsistent with the ID stored in the database, and I found that JavaScript still had this sinkhole!

Due to the reason of Number type in JavaScript, the number of Long type can not be represented completely. When the length of Long is more than 17 bits, the precision will be lost.

When we change the above user ID to 19 bits, let's take a look at the result returned by the browser request.

/ / set user ID with 19-bit user.setId (1234567890123456789l)

The browser requests the result!

When the returned result exceeds 17 digits, the rest becomes 0!

II. Solutions

In such a situation, what should we do?

The first way: change the long type to the String type in the background, but the cost is a little high, as long as it needs to be changed.

The second method: use the tool to convert long type to String type, this method can achieve global conversion (recommended)

The third method: front-end processing (currently there is no good way, not recommended)

Because the project involves a lot of code, it is impossible to change the long type to the String type, and there are many ways to use the Long type, which is very risky, so it is not recommended!

The ideal way is to use the aop agent to intercept all the methods, uniformly handle the return parameters, and convert them using tools, as follows!

1. Jackson tool serializes objects

We can use the Jackson toolkit to serialize objects.

First add the necessary dependencies to maven:

Com.fasterxml.jackson.core jackson-core 2.9.8 com.fasterxml.jackson.core jackson-annotations 2.9.8 com.fasterxml.jackson.core jackson-databind 2.9.8

Write a conversion utility class JsonUtil:

Public class JsonUtil {private static final Logger log = LoggerFactory.getLogger (JsonUtil.class); private static ObjectMapper objectMapper = new ObjectMapper (); private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; all fields of static {/ / object are included in objectMapper.setSerializationInclusion (JsonInclude.Include.ALWAYS) / / cancel the default conversion of timestamps form objectMapper.configure (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); / / ignore the error objectMapper.configure (SerializationFeature.FAIL_ON_EMPTY_BEANS, false) from empty bean to json; / / set to East Zone 8 objectMapper.setTimeZone (TimeZone.getTimeZone ("GMT+8")) / / uniform date format objectMapper.setDateFormat (new SimpleDateFormat (DATE_FORMAT)); / / when deserializing, ignore the situation that it exists in the json string, but does not exist the corresponding attribute in the java object, to prevent the error objectMapper.configure (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) When replacing the sequence with json, change all long to string objectMapper.registerModule (new SimpleModule () .addSerializer (Long.class, ToStringSerializer.instance) .addSerializer (Long.TYPE, ToStringSerializer.instance)) } / * object serialized to json string * @ param obj * @ param * @ return * / public static String objToStr (T obj) {if (null = = obj) {return null;} try {return obj instanceof String? (String) obj: objectMapper.writeValueAsString (obj);} catch (Exception e) {log.warn ("objToStr error:", e); return null }} / * json string deserialization into object * @ param str * @ param clazz * @ return * / public static T strToObj (String str, Class clazz) {if (StringUtils.isBlank (str) | | null = = clazz) {return null } try {return clazz.equals (String.class)? (t) str: objectMapper.readValue (str, clazz);} catch (Exception e) {log.warn ("strToObj error:", e); return null }} / * json strings are deserialized into objects (array) * @ param str * @ param typeReference * @ param * @ return * / public static T strToObj (String str, TypeReference typeReference) {if (StringUtils.isBlank (str) | | null = = typeReference) {return null } try {return (T) (typeReference.getType () .equals (String.class)? Str: objectMapper.readValue (str, typeReference);} catch (Exception e) {log.warn ("strToObj error", e); return null;}

Next, write an entity class Person for testing:

@ Data public class Person implements Serializable {private static final long serialVersionUID = 1L; private Integer id; / / long parameter private Long uid; private String name; private String address; private String mobile; private Date createTime;}

Finally, let's write a test class to test the effect:

Public static void main (String [] args) {Person person = new Person (); person.setId (1); person.setUid (1111L); person.setName ("hello"); person.setAddress (""); System.out.println (JsonUtil.objToStr (person));}

The output is as follows:

The most critical line of code is to register the transformation class so that all long can be changed into string.

When replacing the sequence with json, change all long to string SimpleModule simpleModule = new SimpleModule (); simpleModule.addSerializer (Long.class, ToStringSerializer.instance); simpleModule.addSerializer (Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule (simpleModule)

If you want to format a date, you can set it globally.

/ / Global uniform date format objectMapper.setDateFormat (new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"))

Alternatively, you can set a property individually, such as formatting the createTime attribute as yyyy-MM-dd, with the following comments.

@ JsonFormat (pattern= "yyyy-MM-dd", timezone= "GMT+8") private Date createTime

After the tool conversion class is written, it is very simple. You only need to serialize the parameters returned by the method intercepted by aop, and you can automatically turn all long into string.

2. SpringMVC configuration

If it is a SpringMVC project, the operation is also very simple.

Customize an implementation class that inherits from ObjectMapper:

Package com.example.util; / * inherit ObjectMapper * / 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);}}

Add the following configuration to the configuration file of SpringMVC:

Application/json;charset=UTF-8 text/plain;charset=UTF-8

3. SpringBoot configuration

If it is a SpringBoot project, the operation is similar.

Write a WebConfig configuration class, implement self-WebMvcConfigurer, and override the configureMessageConverters method:

/ * WebMvc configuration * / @ Configuration @ Slf4j @ EnableWebMvc public class WebConfig implements WebMvcConfigurer {/ * add message conversion class * @ param list * / @ Override public void configureMessageConverters (List

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report