最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Servlet response to AJAX request is empty - Stack Overflow

programmeradmin0浏览0评论

I am sending an AJAX request using javascript to a servlet. The servlet is indeed replying but the response header is null and so is the response text.

When I try the same client code to instead send the request to a php page it works fine.

Here are the two clients (you can try them and look at their sources):

  • ajax-to-servlet: http://79.136.61.27/web/ajax-to-servlet.html
  • ajax-to-php: http://79.136.61.27/web/ajax-to-php.html

The output when sending the request to the servlet is:

Response will go below

Response:

responseText was null!

Headers:

null response headers!

The output when sending the request to PHP is:

Response will go below

Response:

Hi from php

Headers:

Date: Sun, 17 Apr 2011 11:58:57 GMT Server: Apache/2.2.17 (Win32) PHP/5.3.6 X-Powered-By: PHP/5.3.6 Content-Length: 18 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html

Here is the code for the servlet. As you can see I am experimenting a bit with settings headers and content type but none of my experiments seem to have any effect. The weird thing is, that I did a hello world-example like this using servlets just recently and it worked just fine without messing with headers and stuff. But now it just does not work anymore. :(

package simple;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SimpleServlet extends HttpServlet {

    private static final long serialVersionUID = -6713061702557291351L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String out = "<p>Hi from servlet!</p>";

        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        System.out.println("got request");

        PrintWriter pw = response.getWriter();

        pw.write(out);
        pw.flush();
        boolean error = pw.checkError();
        System.out.println("Error? " + error);  
    }
}

hifromphp.php is simply:

<?php
    echo "<p>Hi from php</p>";
?>

Thanks for reading and thanks in advance!

Edit: I realized that those links will not work forever. So, for archive purposes I am pasting ajax-to-servlet.html here. ajax-to-php.html is identical except the URL where the request goes. ajax-to-html.html:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
                    ".dtd">
<html xmlns="">
  <head>
    <title>Send ajax</title>
  </head>
  <body>
    <script type="text/javascript">
            /* <![CDATA[ */
            function getXMLHttp() {
                var xmlHttp = new XMLHttpRequest();

                return xmlHttp;
            }

            function sendAjax() {
                var xmlHttp = getXMLHttp();
                var divResp = document.getElementById("response");
                var divHdrs = document.getElementById("responseHeaders");

                xmlHttp.onreadystatechange = function() {
                    if (xmlHttp.readyState == 4) {
                        var hdrs = xmlHttp.getAllResponseHeaders();
                        var resp = xmlHttp.responseText;

                        divHdrs.innerHTML = "<p>Headers:</p><p>" + (hdrs ? hdrs : "null response headers!<p>");
                        divResp.innerHTML = "<p>Response:</p>" + (resp ? resp : "<p>responseText was null!<p>");
                    }
                }       

                xmlHttp.open("GET", "http://79.136.61.27:8080/SimpleServlet/SimpleServlet", true);
                xmlHttp.send(null);
            }
            /* ]]> */
        </script>
    <p><input type="button" value="Send Ajax" onclick="javascript: sendAjax();"/></p>
    <p>Response will go below</p>
    <div id="response"></div>
    <div id="responseHeaders"></div>
  </body>
</html>

I am sending an AJAX request using javascript to a servlet. The servlet is indeed replying but the response header is null and so is the response text.

When I try the same client code to instead send the request to a php page it works fine.

Here are the two clients (you can try them and look at their sources):

  • ajax-to-servlet: http://79.136.61.27/web/ajax-to-servlet.html
  • ajax-to-php: http://79.136.61.27/web/ajax-to-php.html

The output when sending the request to the servlet is:

Response will go below

Response:

responseText was null!

Headers:

null response headers!

The output when sending the request to PHP is:

Response will go below

Response:

Hi from php

Headers:

Date: Sun, 17 Apr 2011 11:58:57 GMT Server: Apache/2.2.17 (Win32) PHP/5.3.6 X-Powered-By: PHP/5.3.6 Content-Length: 18 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/html

Here is the code for the servlet. As you can see I am experimenting a bit with settings headers and content type but none of my experiments seem to have any effect. The weird thing is, that I did a hello world-example like this using servlets just recently and it worked just fine without messing with headers and stuff. But now it just does not work anymore. :(

package simple;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SimpleServlet extends HttpServlet {

    private static final long serialVersionUID = -6713061702557291351L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String out = "<p>Hi from servlet!</p>";

        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        System.out.println("got request");

        PrintWriter pw = response.getWriter();

        pw.write(out);
        pw.flush();
        boolean error = pw.checkError();
        System.out.println("Error? " + error);  
    }
}

hifromphp.php is simply:

<?php
    echo "<p>Hi from php</p>";
?>

Thanks for reading and thanks in advance!

Edit: I realized that those links will not work forever. So, for archive purposes I am pasting ajax-to-servlet.html here. ajax-to-php.html is identical except the URL where the request goes. ajax-to-html.html:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
                    "http://www.w3/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3/1999/xhtml">
  <head>
    <title>Send ajax</title>
  </head>
  <body>
    <script type="text/javascript">
            /* <![CDATA[ */
            function getXMLHttp() {
                var xmlHttp = new XMLHttpRequest();

                return xmlHttp;
            }

            function sendAjax() {
                var xmlHttp = getXMLHttp();
                var divResp = document.getElementById("response");
                var divHdrs = document.getElementById("responseHeaders");

                xmlHttp.onreadystatechange = function() {
                    if (xmlHttp.readyState == 4) {
                        var hdrs = xmlHttp.getAllResponseHeaders();
                        var resp = xmlHttp.responseText;

                        divHdrs.innerHTML = "<p>Headers:</p><p>" + (hdrs ? hdrs : "null response headers!<p>");
                        divResp.innerHTML = "<p>Response:</p>" + (resp ? resp : "<p>responseText was null!<p>");
                    }
                }       

                xmlHttp.open("GET", "http://79.136.61.27:8080/SimpleServlet/SimpleServlet", true);
                xmlHttp.send(null);
            }
            /* ]]> */
        </script>
    <p><input type="button" value="Send Ajax" onclick="javascript: sendAjax();"/></p>
    <p>Response will go below</p>
    <div id="response"></div>
    <div id="responseHeaders"></div>
  </body>
</html>
Share Improve this question edited Jul 6, 2012 at 6:38 RustyTheBoyRobot 5,9634 gold badges38 silver badges55 bronze badges asked Apr 17, 2011 at 12:18 Eric LiljaEric Lilja 3,6234 gold badges19 silver badges17 bronze badges 2
  • Are you running the servlet class you think you're running? – BalusC Commented Apr 17, 2011 at 12:25
  • Thanks for your ment. Yes, I can see how it is invoked and how it responds to changes in the code, so the one I posted is indeed executing. – Eric Lilja Commented Apr 17, 2011 at 12:31
Add a ment  | 

1 Answer 1

Reset to default 3

If you call the servlet standalone it works fine. However, the servlet runs on a different port than where the ajax request is ing from. This violates the Same Origin Policy for ajax requests and thus the browser won't process the ajax response. Apart from hosting the servlet behind the same port, you need to return JSONP or set the HTTP Access-Control headers.

If you want to allow everyone to use the servlet, set the following header:

response.setHeader("Access-Control-Allow-Origin", "*");

The information in the response headers from your links suggests that you're running Apache HTTPD and Apache Tomcat. It's good to know that you can connect Apache HTTPD to Apache Tomcat using Tomcat Connector, it may be more useful.

发布评论

评论列表(0)

  1. 暂无评论