刚开始以为用$.post("b.jsp", { name: "John", time: "22:33" })这样的语句即可搞定,哪知道fiddler出来的结果是,jquery将 { name: "John", time: "22:33" }转为name=Jonh&time=22:33这种url参数再post,因为接收端直接将接收到的字符串转为对象,所以不能用这种方式传输。
后来查google得到答案,用JSON.stringify转一下,将其转为json字符串,jquery就不会自作聪明转为那种形式了:
服务端b.jsp :
pageEncoding="utf8"%>
Insert title hereCommonReqInqBean p_req = CommonReqInqBean.getReqBean(request);
request.setAttribute("cnds", p_req.conditions);
%>
${item.key } : ${item.value.compare } ${item.value.vFrom } and ${item.value.vTo }
查询公共类:
package com.alco.bms.beans;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.core.type.TypeReference;
public class CommonReqInqBean extends AjaxReqInqBean{
public static class ReqObj{
public String compare;
public String vFrom;
public String vTo;
public String getCompare(){
return compare;
}
public String getvFrom(){
return vFrom;
}
public String getvTo(){
return vTo;
}
}
public HashMap conditions; //条件组合
public CommonReqInqBean(){
conditions=new HashMap();
}
public static CommonReqInqBean getReqBean(HttpServletRequest pvRequest) throws Exception{
CommonReqInqBean p_req = null;
HashMap lvFieldC=new HashMap ();
lvFieldC.put("conditions",new TypeReference>(){});
return HttpBeanUtil.beanFromUrlRequestByJsonV1(CommonReqInqBean.class,
new TypeReference() {
}, pvRequest, null,lvFieldC);
}
}
而从request获得递交对象的函数,它兼容两种输入格式,一种是key1=value1&key2=value2的url参数格式,另一种是json字符串格式,用Content-Type里面是否包含"/json"区分:
/***
* 接收已json方式传送的参数,key为_json
*
* @param cl
* @param typeReference
* @param requestParameterMap
* @param outputUploadFiles
* --输出上传文档列表
* @param pvFieldTypes 各字段的value的类信息
* @return
* @throws Exception
*/
public static T beanFromUrlRequestByJsonV1(Class> cl, TypeReference typeReference, HttpServletRequest request,
HashMap outputUploadFiles,HashMap pvFieldTypes) throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
String w_ctype = request.getHeader("Content-Type");
String w_json = "";
if (w_ctype != null && w_ctype.toLowerCase().contains("/json")) {
w_json =getRequestPayload(request);// getRequestContent(request, "utf8");
} else {
w_json = request.getParameter("_json");
}
if (w_json == null) {
return beanFromUrlRequestV1(cl, request.getParameterMap(), true,pvFieldTypes);
} else {
return JsonUtils.readValue(w_json, typeReference);
}
}
ServletFileUpload upload = getUploadObject();
List items;
items = upload.parseRequest(request);
if (items == null)
return null;
T ret = null;
for (FileItem item : items) {
if (item.isFormField() && item.getFieldName().equals("_json")) {
String w_json = new String(item.get(), "UTF-8");
ret = JsonUtils.readValue(w_json, typeReference);
}
if (outputUploadFiles != null) {
if (item.isFormField())
continue;
String w_fname = "";
try {
w_fname = item.getName();
w_fname = w_fname.substring(w_fname.lastIndexOf("\\") + 1);
w_fname = w_fname.substring(w_fname.lastIndexOf("/") + 1);
} catch (Exception p_e) {
}
// Skip Empty Field
if (w_fname.compareTo("") == 0)
continue;
outputUploadFiles.put(item.getFieldName(), item);
}
}
return ret;
}
若客户端用了JSON.stringify转换,并在contentType里面加入"/json",则服务端 会用JsonUtils.readValue返回对象。
来个完整的例子:
$.ajax({type:"post",
url:"b.jsp",
data:JSON.stringify({"pagenum":0,"pagesize":100,"sortdatafield":"line","conditions":m_QryUtil.getResults()}),
contentType: "application/xml ;/json; charset=utf-8"
}).done(function (data){
alert(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
我们看一下fiddler2的数据包:
POST http://128.30.200.217/bms/b.jsp HTTP/1.1
Host: 128.30.200.217
Connection: keep-alive
Content-Length: 216
Accept: */*
Origin: http://128.30.200.217
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
Content-Type: application/xml ;/json; charset=UTF-8
Referer: http://128.30.200.217/bms/b.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=11ED4F5F4C4079972AD0C9536B10D205
{"pagenum":0,"pagesize":100,"sortdatafield":"line","conditions":{"jobno":{"compare":"=","vFrom":"JB046620G"},"model":{"compare":"=","vFrom":"CT9773","vTo":""},"keypart":{"compare":"Between","vFrom":"11","vTo":"22"}}}用JSON.stringify转一下,递交时就会以json 字符格式递交。
若客户端用key=value这种形式递交(比如传统的form submit),以或者递交的数据没转换:
$.post("b.jsp",{"pagenum":0,"pagesize":100,"sortdatafield":"line","conditions":JSON.stringify(m_QryUtil.getResults())},
function(data){
alert(data);
});那么服务端将会用beanFromUrlRequestV1方法转换得到查询对象。
我们再看一下这个请求产生的数据包:
POST http://128.30.200.217/bms/b.jsp HTTP/1.1
Host: 128.30.200.217
Connection: keep-alive
Content-Length: 336
Accept: */*
Origin: http://128.30.200.217
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://128.30.200.217/bms/b.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=11ED4F5F4C4079972AD0C9536B10D205
pagenum=0&pagesize=100&sortdatafield=line&conditions=%7B%22jobno%22%3A%7B%22compare%22%3A%22%3D%22%2C%22vFrom%22%3A%22JB046620G%22%7D%2C%22model%22%3A%7B%22compare%22%3A%22%3D%22%2C%22vFrom%22%3A%22CT9773%22%2C%22vTo%22%3A%22%22%7D%2C%22keypart%22%3A%7B%22compare%22%3A%22Between%22%2C%22vFrom%22%3A%2211%22%2C%22vTo%22%3A%2222%22%7D%7D
本文探讨了使用jQuery发送POST请求时,如何正确地传递JSON格式的数据而非URL编码的参数。通过JSON.stringify方法转换数据并设置合适的Content-Type,可以确保服务器端能够正确解析请求中的复杂数据结构。
318

被折叠的 条评论
为什么被折叠?



