服务器端代码如下:
@RequestMapping(value = "/test")
@ResponseBody
public Result test(){
result.setSuccess(true);
result.setData(new Random().nextDouble() + System.currentTimeMillis());
return result;
}
chorme的network截图如下,发现两次请求返回的内容是同一个
请求一
请求二
经过多次试验,发现请求是都走到Controller里,但是第一次请求的响应数据没有马上返回给浏览器端,而是和第二次请求的响应一起返回给了前端,并且第一次请求的响应内容居然是第二次响应的内容。
有时候两次请求的响应能不相同,有时候却相同,不知道是什么原因。
我的实际应用场景是,前台上传多个附件,但是本质是多次上传,然后由后台返回此文件在数据库中的文件id。然后我发现有时上传多个文件时,返回的文件id都是同一个。
如下图所示:两个上传的文件长度是不一样的
文件一
文件二
但是服务器返回的文件id却是一样的:
文件一
文件二
文件一
请求消息
响应消息
文件二
请求消息
响应消息
Try adding a timestamp to prevent caching after the URL requested by the browser
After reading the comments, it may be that case. Take a look at the response code. If it is 304, it will be the same as last time. Because the requested URL is the same, you can add a random parameter (timestamp) to the request to cache the data used by the browser to ensure that the URL is inconsistent each time.
Look at the log of spring mvc controller to see if the time when the request reaches the server is the same millisecond
Chief, you are here again, try using
System.nanoTime()
and see the return value.Due to the lack of important information such as request data (is it a GET request or a POST request? How are these two requests initiated? How is the relevant client code written?), the following is only a personal guess:
1. You two The requests were initiated to the server almost at the same time;
2. Based on the guess of 1,
new Random().nextDouble() + System.currentTimeMillis()
It can almost be considered that the difference is not big (especially when testing locally);3. You used double to store this random number, and then jackson Precision loss may occur when serializing double values (please search for the precision loss problem of js by yourself), so on the client side, your two values will appear to be exactly the same;
Based on the conjecture of 1, the hypothetical verification method is as follows:
Look at the output results, and use JSON.parse (the value logged) in the console of the browser to see if they are the same.
Solution: Use a string to store this random number. The following is a method I wrote myself to generate several digits of random numbers (java8):
As for the problem after your dividing line, there is no code and it cannot be analyzed.
On the server side, print the requested URL path parameters to the console. The two requests printed to the server should be exactly the same, so the server handles them as one request. You can try the above System.nanoTime(); method.