servlet - 为什么XMLHttpRequest responseText总是空白?

时间:2015-03-18 16:24:14

标签: javascript ajax tomcat servlets

我正试图在这里解决这个问题。我在Tomhost上运行了以下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。我使用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上运行所有内容。

为什么这仍然会发生?我该如何解决?

1 个答案:

答案 0 :(得分:0)

好的解决了。猜猜这是我自己的愚蠢错误。 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()的请求中找到结果。