Servlet response to AJAX request is empty

11,637

If you call the servlet standalone it works fine. However, the servlet runs on a different port than where the ajax request is coming 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.

Share:
11,637
Eric Lilja
Author by

Eric Lilja

Updated on June 04, 2022

Comments

  • Eric Lilja
    Eric Lilja almost 2 years

    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.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/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>
    
  • Eric Lilja
    Eric Lilja about 13 years
    Thank you so much, BalusC, your analysis was indeed correct. I made it work using the Tomcat Connector. Thanks alot!