1. 程式人生 > >Jsp頁面傳Json資料到服務端,轉物件或集合進行資料處理

Jsp頁面傳Json資料到服務端,轉物件或集合進行資料處理

需求:1、將頁面資料帶到服務端並轉成物件,2、將頁面的集合資料帶到服務端轉List
實現:用ajax請求傳遞資料,資料格式為json

JS方法:

testJsonMethod = function(){
	// 員工資訊
	var employeeInfo = {
		emplNum : '123',
		emplName : 'lee',
		telNum : '18888888888'
	};
	// 標籤資訊
	var dataParam = [];
	for(var i=0; i<3; i++){
		var employeeLabel = {
			labelName : 'name' + i,
			labelOrder : i,
			labelRemarks : 'remark' + i
		}
		dataParam.push(employeeLabel);
	}
	var jsonEmployee = JSON.stringify(employeeInfo);
	var jsonLabelList = JSON.stringify(dataParam);

	// cache  Boolean (預設: true) 設定為 false 將不會從瀏覽器快取中載入請求資訊。
	// async  Boolean (預設: true) 預設設定下,所有請求均為非同步請求。如果需要傳送同步請求,請將此選項設定為 false。注意,同步請求將鎖住瀏覽器,使用者其它操作必須等待請求完成才可以執行
	$.ajax({
		type : 'post',
		url : '${ctx}/admin/employee/testJsonMethod',
		data : {jsonEmployee:jsonEmployee, jsonLabelList:jsonLabelList},
		cache : false,
		dataType : 'json',
		success : function(data){
			alert(data);
		},
		error : function() {
			alert("異常!");
		}
	});
}
服務端方法:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RequestMapping(value = "/testJsonMethod", method = RequestMethod.POST)
public ModelAndView testJsonMethod(String jsonEmployee, String jsonLabelList) throws Exception {
	SysEmployeeInfo sysEmployeeInfo = (SysEmployeeInfo) JSONObject.toBean(JSONObject.fromObject(jsonEmployee), SysEmployeeInfo.class);
	List<SystLabelInfo> systLabelInfoList = (List<SystLabelInfo>) JSONArray.toCollection(JSONArray.fromObject(jsonLabelList), SystLabelInfo.class);
	return new ModelAndView(JSON_VIEW).addObject(Constant.RETURN, true);
}