最近學(xué)習(xí)了springmvc 接收json對象的兩種方式,現(xiàn)在整理出來,具體如下:
1、以實體類方式接收
前端 ajax 提交數(shù)據(jù):
function fAddObj() { var obj = {}; obj['objname'] = "obj"; obj['pid'] = 1 ; $.ajax({ url: 'admin/Obj/addObj.do', method: 'post', contentType: 'application/json', // 這句不加出現(xiàn)415錯誤:Unsupported Media Type data: JSON.stringify(obj), // 以json字符串方式傳遞 success: function(data) { console.log("success..."); }, error: function(data) { console.log("error..."); } });}
springmvc 以model對象的形式接收:
@Controller@RequestMapping("/admin/Obj")public class ObjAction { // 注入操作類 @Autowired private ObjService objService ; @RequestMapping(value = "/addObj") @ResponseBody public String addObj(@RequestBody Obj obj) { this.objService.insertObj(cate); return "success"; }}
2、以Map接收
@Controller@RequestMapping("/admin/Obj")public class ObjAction { /** * 前端操作與上面相同 * @return */ @RequestMapping(value = "/updateAttr") @ResponseBody public String updateAttr(@RequestBody Map<String, String> map) { if(map.containsKey("id"){ Integer id = Integer.parseInt(map.get("id")); } if(map.containsKey("objname"){ String objname = map.get("objname").toString(); } if(map.containsKey("pid"){ Integer pid = Integer.parseInt(map.get("pid")); } // 操作 ... return "success"; }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答