加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

AJAX POST请求中参数以form data和request payload形式在servlet

发布时间:2020-12-15 21:29:38 所属栏目:百科 来源:网络整理
导读:之前写了一个post请求如下: $.ajax({ url:"register", type:"POST", contentType:"text/json;charset=UTF-8", data:{ "useringId":useringId }, error : function() { alert('发生错误,请重试!'); }, success:function(data){ if(data.status==1){ $(_thi

之前写了一个post请求如下:

$.ajax({

url:"register",

type:"POST",

contentType:"text/json;charset=UTF-8",

data:{
"useringId":useringId
},
error : function() {
alert('发生错误,请重试!');
},
success:function(data){
if(data.status==1){
$(_this).parent().html("<span>已转为正式用户</span>");
}
else if(data.status==2){
alert("后台错误!");
}
}

});

请求报400,一看参数,发现useringId这个参数在request payload中。大致如下:


  1. RequestURL:http://127.0.0.1:8080/test/test.do
  2. RequestMethod:POST
  3. StatusCode:200OK
  4. RequestHeaders
  5. Accept:*/*
  6. Accept-Encoding:gzip,deflate,sdch
  7. Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
  8. AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2
  9. Connection:keep-alive
  10. Content-Length:28
  11. Content-Type:text/plain;charset=UTF-8
  12. Cookie:JSESSIONID=C40C7823648E952E7C6F7D2E687A0A89
  13. Host:127.0.0.1:8080
  14. Origin:http://127.0.0.1:8080
  15. Referer:http://127.0.0.1:8080/test/index.jsp
  16. User-Agent:Mozilla/5.0(WindowsNT6.1)AppleWebKit/537.36(KHTML,likeGecko)Chrome/33.0.1750.149Safari/537.36
  17. RequestPayload
  18. useringId=9
  19. ResponseHeaders
  20. Content-Length:2
  21. Date:Sun,11May201411:49:23GMT
  22. Server:Apache-Coyote/1.1

百度后得知,这是由于contentType引起的“误会”。


jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,所以服务器能够按键值对方式正确解析,而使用原生ajax请求,如果不显示的设置Content-Type,那么默认是text/plain,或设置contentType不是application/x-www-form-urlencoded这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。


解析方式如下:

  1. privateStringgetRequestPayload(HttpServletRequestreq){
  2. StringBuildersb=newStringBuilder();
  3. try(BufferedReaderreader=req.getReader();){
  4. char[]buff=newchar[1024];
  5. intlen;
  6. while((len=reader.read(buff))!=-1){
  7. sb.append(buff,0,len);
  8. }
  9. }catch(IOExceptione){
  10. e.printStackTrace();
  11. }
  12. returnsb.toString();
  13. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读