servlet-为什么XMLHttpRequest responseText始终为空

servlet - Why is the XMLHttpRequest responseText always blank?

本文关键字:responseText 为什么 XMLHttpRequest servlet-      更新时间:2023-09-26

我在试图解决这里的这个问题时失去了理智。我在Tomcat中部署了以下servlet,运行在localhost: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。I代码在带有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()上提出的请求中找到结果。