使AJAX POST请求的Servlet失败 [英] Making AJAX POST request to Servlet fails

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

问题描述

这是我的客户端code,我想提出一个AJAX调用我的servlet。如果我使用GET作为请求方法。一切正常,我也得到响应返回。但是,当我发出请求为POST,servlet的不发送响应。从日志中我发现,当制作与邮政Ajax调用,在servlet的请求对象为空。根据这篇文章: Servlet的响应AJAX请求是空的,我设置的头同源策略。

From my client side code, I am making an AJAX call to my servlet. If I use GET as request method. Everything works and I get response back. But when I send request as POST, servlet fails to send the response. From log I found out that in servlet "request" object is null when made ajax call with POST. According to this post: Servlet response to AJAX request is empty , I'm setting headers for same-origin policy.

下面是我的code,以供参考:

Below is my code for reference:

function aimslc_ajaxCall(url,callback, postParams){
  var xmlhttp = null
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
    eval( callback+"("+xmlhttp.responseText+")" );
    }
  }

  if(postParams!=null && typeof postParams!="undefined" ){
            xmlhttp.open("POST",url,true);
    xmlhttp.send(postParams);
  }else{
            xmlhttp.open("GET",url,true);
        xmlhttp.send();
  }
}

Servlet的code:

Servlet Code:

 public void doProcess (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      logger.info("doProcess::start..."+request.getQueryString());
      response.setHeader("P3P","CP='NOI ADM DEV PSAi COM NAV OUR OTR STP IND DEM'");
  response.setHeader("Access-Control-Allow-Origin","*");
  response.setHeader("Access-Control-Allow-Credentials","true");
  response.setHeader("Access-Control-Allow-Methods","POST, GET");
 }

抛出的request.getQueryString空异常()

Throws a null exception on request.getQueryString()

推荐答案

如果你做一个职位的所有数据是在请求主体,而不是在URL。从<一个href="http://java.sun.com/javaee/6/docs/api/javax/servlet/http/HttpServletRequest.html#getQueryString%28%29"相对=nofollow>此处你看到 getQueryString 只拿到东西​​的URL。

if you do a post all the data is in the request body, not on the url. From here you see that getQueryString only gets the stuff on the url.

请参阅<一href="http://stackoverflow.com/questions/5023718/how-to-retreive-raw-post-data-from-httpservletrequest-in-java">here对于如何获得请求主体。

See here for how to get the request body.

另外,如果你的数据是名/值对,您可能需要使用的的getParameter 和相关方法。

Also, if your data is name/value pairs, you might want to use getParameter and associated methods.

如果请求是空的,我问你实施的doPost 在你的servlet?

If the request is null, I ask do you implement doPost on your servlet?

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

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