#author("2019-11-18T16:29:34+08:00","default:Admin","Admin") SpringMVC 概要 †@ResponseBody的作用其实是将java对象转为json格式的数据。 @responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。 @ResponseBody是作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】。 依赖 †添加依赖 springmvc对json的处理依赖jackson <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.11</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.11</version> </dependency> xml配置 †<mvc:annotation-driven />//不要忘了命名空间配置 使用方法 †单层嵌套json对象 †使用@RequestParam $.ajax({ type : "post", dataType : "json", url : "/testRequestBody", data:{ name:"韦德", age:35 }, success : function(result) { } }); @RequestMapping("/testRequestBody") public String testRequestBody(@RequestParam Map<String, Object> map) { System.out.println(map);// {name=韦德, age=35} return "index"; } 多层嵌套json对象 †$.ajax({ type : "post", dataType : "json", url : "/testResponseBody", success : function(result) { console.info(result); } }); @RequestMapping("/testResponseBody") @ResponseBody public Map<String, Object> testRequestBody() { Map<String, Object> result = new HashMap<String, Object>(); result.put("name", "韦德"); result.put("age", 35); return result; } 月額たった 1,050円で始められる本格的なお店のホームページ! コメント: |