我无法为用户建立 AsyncContexts 并使用它们向他们推送通知。在页面加载时,我有一些 jQuery 代码来发送请求:
$.post("TestServlet",{
action: "registerAsynchronousContext"
},function(data, textStatus, jqXHR){
alert("Server received async request"); //Placed here for debugging
}, "json");
在“TestServlet”中,我在 doPost 方法中有以下代码:
HttpSession userSession = request.getSession();
String userIDString = userSession.getAttribute("id").toString();
String paramAction = request.getParameter("action");
if(paramAction.equals("registerAsynchronousContext"))
{
AsyncContext userAsyncContext = request.startAsync();
HashMap<String, AsyncContext> userAsynchronousContextHashMap = (HashMap<String, AsyncContext>)getServletContext().getAttribute("userAsynchronousContextHashMap");
userAsynchronousContextHashMap.put(userIDString, userAsyncContext);
getServletContext().setAttribute("userAsynchronousContextHashMap", userAsynchronousContextHashMap);
System.out.println("Put asynchronous request in global map");
}
//userAsynchronousContextHashMap is created by a ContextListener on the start of the web-app
但是,根据 Opera Dragonfly(一种调试工具,如 Firebug),似乎服务器在请求发送后大约 30000 毫秒发送了 HTTP 500 响应。
使用 userAsyncContext.getResponse().getWriter().print(SOME_JSON) 创建并在 HTTP 500 响应之前发送的任何响应都不会被浏览器接收,我不知道为什么。仅当处理 AsyncContext 的“if”语句中的所有代码都不存在时,浏览器才会接收使用常规响应对象发送响应 (response.print(SOME_JSON))。
有人可以帮我吗?我有一种感觉,这是由于我对异步 API 的工作原理有误解。我认为我可以将这些 AsyncContexts 存储在全局映射中,然后检索它们并使用它们的响应对象将内容推送给客户端。但是,似乎 AsyncContexts 不能写回客户端。
任何帮助将不胜感激。