我在试图解决这里的问题时失去了理智。我在本地主机上运行的 Tomcat 中部署了以下 servlet:8080-:
@WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true)
public class CreateCon extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
ConcurrentHashMap<String, AsyncContext> map;
public CreateCon() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void init() {
map = new ConcurrentHashMap<>();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext context = request.startAsync(request,response);
context.setTimeout(10000);
if(!map.containsKey("Hello"))
map.put("Hello", context);
System.out.print("Inside GET");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext context = map.get("Hello");
PrintWriter writer = context.getResponse().getWriter();
writer.write(request.getParameter("message"));
writer.flush();
System.out.print(request.getParameter("message"));
}
}
如您所见,我正在尝试存储在 Map 中创建的 AsyncContext。我的代码在带有 Tomcat 的 Eclipse 中运行良好。正如您在上面看到的,我添加了 System.out.print
来实际检查代码是否正常工作。而且它完全按照预期工作。
但问题出在下面的 javascript-:
function postMessage(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "/SampleTest/createcon", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var messageText = escape(document.getElementById("i1").value);
document.getElementById("i1").value = "";
xmlhttp.send("message="+messageText);
}
onreadystatechange
准确地按预期触发,但 xmlhttp.responseText
始终为空白。
我知道有一种叫做同源策略的东西。但我不明白为什么这是个问题?我在 localhost:8080
上运行所有内容。
为什么这仍然发生,我该如何解决?
最佳答案
好的解决了。猜猜这是我自己的愚蠢错误。 startchat() 方法应该修改为:
function startChat() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/SampleTest/createcon", true);
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
}
因为我试图从在 startChat()
发出的请求中找到结果。
关于javascript - servlet - 为什么 XMLHttpRequest 响应文本总是空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29127384/