var jsonData = jsonToStr($('#addForm').serializeArray());//json数据 $.ajax({ type:"POST", url:"service/basic/department/add.json", dataType:"json", data:"_data_=" + jsonData, success: function(data) { if (!data.result) { alert(data.remark); } else { alert("添加部门成功..."); window.returnValue = "success"; window.close(); } }, error:function(error) { alert("操作失败:error message:" + error.statusText); } });
因为后台定义的接受格式是_data_;所以data:"_data_"+ json;
@RequestMapping(value = "/add", method = RequestMethod.POST) public String create(HttpServletRequest request, Model model) { ResponseVO<Department> response = new ResponseVO<Department>(); try { Department department = DataMapping.mapping(request, Department.class); // 前台设置仓库改为后台设置仓库。。 Warehouse warehouse = new Warehouse(); warehouse.setId(DataMapping.getWareHourse(request).getId()); department.setWarehouse(warehouse); department = departmentService.create(department); response.setResult(true); Department data = new Department(); data.setId(department.getId()); response.setData(data); } catch (Exception ex) { log.error("Exception", ex); AppException exception = ExceptionHandleUtil.handle(ex); response.setResult(false); response.setCode(exception.getCode()); response.setRemark(exception.getMessage()); ex.printStackTrace(); } model.addAttribute(response); return "success"; } public static <T> T mapping(HttpServletRequest request, Class<T> clazz) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); String data = request.getParameter("_data_"); return objectMapper.readValue(data, clazz); }
json中的key对应实体类中的属性必须保持一致
spring mvc前台传json值 后台接受处理成object
最新推荐文章于 2021-11-22 17:11:48 发布