用jQuery Post json对象、java端接收并还原为查询参数对象

17 篇文章 0 订阅
14 篇文章 0 订阅

    刚开始以为用$.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 :

<%@ page import="com.alco.bms.beans.CommonReqInqBean" %>
<%@ page import="com.alco.bms.beans.CommonReqInqBean.*" %>
<%@page import="com.alco.bms.beans.HttpBeanUtil"%>
<%@page import="java.util.HashMap"%>
<%@page import="com.fasterxml.jackson.core.type.TypeReference"%>
<%@page import="com.freestyle.utils.Util"%>

<%@ page language="java" contentType="text/html; charset=utf8"
    pageEncoding="utf8"%>
<%@ page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>Insert title here</title>
</head>
<%
CommonReqInqBean p_req = CommonReqInqBean.getReqBean(request);
request.setAttribute("cnds", p_req.conditions);
%>
<body>
<%=p_req.conditions.get("jobno").vFrom%>
<br/>
<c:forEach items="${cnds}" var="item">
	<li>
		${item.key } : ${item.value.compare } ${item.value.vFrom }  and  ${item.value.vTo }
	</li>
	<br/>
</c:forEach>
</body>
</html>


查询公共类:

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<String,ReqObj> conditions; //条件组合
	public CommonReqInqBean(){
		conditions=new HashMap<String,ReqObj>();
	}
	public static CommonReqInqBean getReqBean(HttpServletRequest pvRequest) throws Exception{
		CommonReqInqBean p_req = null;
		HashMap<String,TypeReference> lvFieldC=new HashMap<String,TypeReference> ();
		lvFieldC.put("conditions",new TypeReference<HashMap<String,ReqObj>>(){});
		
			return HttpBeanUtil.beanFromUrlRequestByJsonV1(CommonReqInqBean.class,
					new TypeReference<CommonReqInqBean>() {
					}, 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> T beanFromUrlRequestByJsonV1(Class<?> cl, TypeReference typeReference, HttpServletRequest request,
			HashMap<String, FileItem> outputUploadFiles,HashMap<String,TypeReference> 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<FileItem> 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返回对象。

  来个完整的例子:

<script>
$.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);
		});

</script>


我们看一下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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值