Java Servlets - Ajax请求带有混合响应 [英] Java Servlets - Ajax requests come back with mixed responses

查看:140
本文介绍了Java Servlets - Ajax请求带有混合响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一些奇怪的结果,几乎同时向同一个java servlet发送多个异步AJAX调用。

I'm getting some strange results sending multiple asynchronous AJAX calls to the same java servlet at the roughly the same time.

例如,假设我发送两个AJAX请求同时使用jQuery。

For example, let's say I send off two AJAX requests at the same time using jQuery.

//ajax call foo
$.post('LookupServlet', {
  method: 'findFoo'
};

//ajax call bar
$.post('LookupServlet', {
  method: 'findBar'
};

在我的servlet中它调用给定的方法。该方法写一个对流的响应。

In my servlet it invokes the given method. The method writes a response to the stream.

奇怪的是foo有时会得到bar的响应。反之亦然。或者有时一个ajax调用得到两个响应。或者一个请求获得响应而另一个请求没有。

What is strange is that that foo sometimes gets the response for bar. And vice versa. Or sometimes one ajax call is getting both responses. Or one request gets a response and the other one doesn't.

我之前从未见过其他服务器端语言中的任何内容,我甚至都不知道有可能。有没有人有任何关于为什么会这样的理论? Java servlet如何在同时请求可以得到交叉响应的情况下运行?

I've never seen anything quite like this before in other server-side languages, I didn't even know it was possible. Does anyone have any theories as to why this is happening? How do Java servlets operate where simultaneous requests could get crossed responses?

推荐答案

可能的原因是servlet是不写为线程安全。请注意,包含servlet方法的对象可用于响应许多同时发出的请求。如果该方法使用类级别变量来创建响应,则请求将显示为混淆。

The likely cause is that the servlets are not written to be thread safe. Note that the object that contains the servlet methods may be used to respond to many simultaneous requests. If that method uses a class level variable to create the response, then requests will appear to get 'mixed up'.

所以..请求#1进入,被分配到一个Servlet的实例,实例#1

So.. Request #1 comes in, is assigned to an instance of Servlet, Instance #1

在Instance#1上调用适当的方法,它开始使用类变量来计算结果。实例#1.myVariable =Blah

The appropriate method is invoked on Instance #1, which starts using a class variable to calculate the result. Instance #1.myVariable = "Blah"

现在,请求#2进来,也分配给实例#1

Now, Request #2 comes in, is also assigned to Instance #1

同样,在Instance#1上调用适当的方法,它设置Instance#1.myVariable =Foo

Again, the appropriate method is invoked on Instance #1, which sets Instance #1.myVariable ="Foo"

..同时第一个请求完成,并返回Instance#1.myVariable ...Foo!

.. in the mean time the first request completes, and returns Instance #1.myVariable... "Foo"!

..然后第二个请求完成,并返回Foo。

.. and then the second request completes, and also returns "Foo".

这篇关于Java Servlets - Ajax请求带有混合响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆