一般web端都是用form標簽的形式進行表單提交到后台,后台控制層再用相應的實體對象去接收前端傳來的json參數。
但是有時候前端界面很復雜,要傳入后端的參數是各種標簽里面的value值,這些值又是來自不同實體對象,所以后台接收參數就會變成一個麻煩事。
我現在采取的措施是,后端控制層用一個map參數接分別來自三個不同對象的屬性。不過要事先在前端封裝好json對象。
(實際場景是微信公賬號)
1.前端代碼
submitSave:function (){ var data = { "visitorInfo":{},//預約信息 "license":{},//車輛信息 "user":{}//當前登錄用戶信息 }; data.license.carNo = vm.carNo; data.visitorInfo.originatorType = vm.userType; data.visitorInfo.createId = vm.createId; data.visitorInfo.userId = vm.userId; data.visitorInfo.receiverId = vm.receiverId; data.visitorInfo.invitationReason = vm.invitationReason; data.visitorInfo.ddr = vm.ddr; data.visitorInfo.invitationTime = vm.invitationTime; data.visitorInfo.endTime = vm.endTime; data.user.id = vm.dengluId; // console.log(JSON.stringify(data)) $.ajax({ url: '${ctx}/mobile/submit', dataType: 'json', contentType : 'application/json;charset=utf-8',//缺少這個415 type: 'post', data: JSON.stringify(data),//缺少這個400 success: function (data) { console.log(data); if (data.status == 1) { setTimeout(function () { // mui.back(); //跳到首頁 window.location.href = '${ctx}/mobile/toIndex'; }, 1000) } if(data.status == 0){ } if(data.msg != ''){ mui.toast(data.msg); } } }); },
2.后台代碼(中間map用阿里的fastjson解析)
/** * 提交和修改按鈕接口 */ @ResponseBody @PostMapping("/submit")public ResponseEntity<Response> submit(@RequestBody Map<String,Object> map,HttpServletRequest request) { Map<String,String> map1 = (Map) map.get("visitorInfo"); Map<String,String> map2 = (Map) map.get("license"); Map<String,String> map3 = (Map) map.get("user"); VisitorInfo visitorInfo = JSON.parseObject(JSON.toJSONString(map1), VisitorInfo.class); License license = JSON.parseObject(JSON.toJSONString(map2), License.class); UserInfo user = JSON.parseObject(JSON.toJSONString(map3), UserInfo.class); }