Servlet的响应AJAX请求是空的 [英] Servlet response to AJAX request is empty

查看:203
本文介绍了Servlet的响应AJAX请求是空的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发送使用JavaScript来一个servlet AJAX请求。该servlet确实答复,但响应头为空,所以是响应文本。

当我尝试在同一客户端code来代替请求发送到PHP页面正常工作。

下面是两个客户端(你可以尝试一下,看看他们的源):

  • AJAX到的servlet:<打击> http://79.136.61.27/web/ajax-to-servlet.html
  • AJAX到PHP:<打击> http://79.136.61.27/web/ajax-to-php.html

发送请求到Servlet时的输出是:

 响应会低于

响应:

responseText的为空!

头:

空响应头!
 

将请求发送到PHP时的输出是:

 响应会低于

响应:

从PHP喜

头:

日期:太阳,2011 4月17日11时58分57秒格林尼治标准​​时间服务器:Apache / 2.2.17(Win32的)PHP / 5.3.6的X技术,通过:PHP / 5.3.6的Content-Length:18保持活动:超时= 5,最大值= 100连接:保持活动的Content-Type:text / html的
 

下面是code为Servlet。正如你所看到的,我尝试了一下与设置标题和内容类型,但没有我的实验似乎有任何影响。奇怪的是,我做了一个Hello World,例如像这样使用servlet最近刚刚和它的工作只是罚款而不报头之类的东西搞乱。但现在它只是不工作了。 :(

 包装简单;

进口java.io.IOException异常;
进口的java.io.PrintWriter;

进口javax.servlet.ServletException;
进口javax.servlet.http.HttpServlet的;
进口javax.servlet.http.HttpServletRequest;
进口javax.servlet.http.HttpServletResponse;


公共类SimpleServlet延伸的HttpServlet {

    私有静态最后长的serialVersionUID = -6713061702557291351L;

    保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{
        串出=&LT; P&GT;从喜的servlet&LT;!/ P&gt;中;

        response.setContentType(为text / xml);
        response.setHeader(缓存控制,无缓存);
        的System.out.println(有要求);

        PrintWriter的PW = response.getWriter();

        pw.write(出);
        pw.flush();
        布尔错误= pw.checkError();
        的System.out.println(?错误+误差);
    }
}
 

hifromphp.php很简单:

 &LT; PHP
    从PHP&LT喜;&LT; P&GT / P&gt;中回声;
?&GT;
 

感谢您的阅读,并在此先感谢!

编辑:我意识到,这些链接将无法工作下去。因此,用于存档,我粘贴AJAX到servlet.html这里。 AJAX到php.html是除非请求进入的网址相同。 AJAX到中将Html.HTML:

 &LT; XML版本=1.0编码=UTF-8&GT?;
!&LT; D​​OCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0 Strict标准// EN
                    http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
&LT; HTML的xmlns =htt​​p://www.w3.org/1999/xhtml&GT;
  &LT; HEAD&GT;
    &LT;冠军&GT;发送AJAX&LT; /标题&GT;
  &LT; /头&GT;
  &LT;身体GT;
    &LT;脚本类型=文/ JavaScript的&GT;
            / *&LT;![CDATA [* /
            传播getXMLHttp(){
                VAR XMLHTTP =新XMLHtt prequest();

                返回XMLHTTP;
            }

            传播sendAjax(){
                VAR XMLHTTP = getXMLHttp();
                VAR divResp =的document.getElementById(回应);
                变种divHdrs =的document.getElementById(responseHeaders响应);

                xmlHttp.onreadystatechange =功能(){
                    如果(xmlHttp.readyState == 4){
                        VAR HDRS = xmlHttp.getAllResponseHeaders();
                        VAR RESP = xmlHttp.responseText;

                        divHdrs.innerHTML =&其中p为H.;集管:其中; / P&GT;&其中; P&gt;中+(HDRS HDRS:?!零响应头&LT; P&gt;中);
                        divResp.innerHTML =&其中p为H.;响应:其中; / P&gt;中+(RESP RESP:?&LT; P&GT;的responseText为空&LT; P&GT;!);
                    }
                }

                xmlHttp.open(GET,http://79.136.61.27:8080/SimpleServlet/SimpleServlet,真正的);
                xmlHttp.send(空);
            }
            / *]]≥ * /
        &LT; / SCRIPT&GT;
    &LT; P&GT;&LT;输入类型=按钮值=发送Ajax的的onclick =JavaScript的:sendAjax();/&GT;&LT; / P&GT;
    &LT; P&GT;响应会低于&LT; / P&GT;
    &LT; D​​IV ID =响应&GT;&LT; / DIV&GT;
    &LT; D​​IV ID =responseHeaders响应&GT;&LT; / DIV&GT;
  &LT; /身体GT;
&LT; / HTML&GT;
 

解决方案

如果你调用servlet 独立它工作正常。然而,该servlet运行在不同的端口不到哪里Ajax请求是来自上。这违反了同源策略的Ajax请求,因此浏览器将不处理Ajax响应。除了托管背后的同一端口的服务器小程序,需要返回 JSONP 或设置 HTTP 访问控制 头。

如果你想允许的每个人的使用servlet中,设置以下标题:

  response.setHeader(访问控制 - 允许 - 起源,*);
 

这是你的链接在响应头中的信息表明,你正在运行的Apache httpd和Apache Tomcat的。这是很好的了解,您可以使用 Tomcat连接器连接的Apache的httpd到Apache Tomcat,也可能是更为有用。

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>

解决方案

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.

这篇关于Servlet的响应AJAX请求是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆