这里有新鲜出炉的精品教程, 程序狗速度看过来!
Spring Framework 开源 j2ee 框架
Spring 是什么呢? 首先它是一个开源的项目, 而且目前非常活跃; 它是一个基于 IOC 和 AOP 的构架多层 j2ee 系统的框架, 但它不强迫你必须在每一层 中必须使用 Spring, 因为它模块化的很好, 允许你根据自己的需要选择使用它的某一个模块; 它实现了很优雅的 MVC, 对不同的数据访问技术提供了统一的接口, 采用 IOC 使得可以很容易的实现 bean 的装配, 提供了简洁的 AOP 并据此实现 Transcation Managment, 等等
本篇文章主要介绍了 springMvc 注解之 @ResponseBody 和 @RequestBody 详解, 小编觉得挺不错的, 现在分享给大家, 也给大家做个参考一起跟随小编过来看看吧
简介
springmvc 对 json 的前后台传输做了很好封装, 避免了重复编码的过程, 下面来看看常用的 @ResponseBody 和 @RequestBody 注解
添加依赖
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 />// 不要忘了命名空间配置
- @ResponseBody
如果传输的是单层 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 对象, 这个时候会就会出现数据丢失问题
@ResponseBody 很好的解决了这个问题, 它会把前台传输过来的 json 转化为后台对应的对象
- $.ajax({
- type : "post",
- dataType : "json",
- url : "/testRequestBody",
- contentType:"application/json",
- data:JSON.stringify({
- name:"韦德",
- win:[2006,2012,2013],
- age:35
- }),
- success : function(result) {
- }
- });
- @RequestMapping("/testRequestBody")
- public String testRequestBody(@RequestBody Map<String, Object> map) {
- System.out.println(map);//{name = 韦德, win=[2006, 2012, 2013], age=35}
- return "index";
- }
需要注意的是前台需要指定 contentType 为 "application/json"
同时要把 json 对象转化为 String, 否则后台不能识别
@ResponseBody
ajax 请求返回 json 格式, 往常我们可以这样做
- private void writeJson(HttpServletResponse response, Object object) {
- String json = JSON.toJSONString(object);
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application/json; charset=utf-8");
- PrintWriter out = null;
- try {
- out = response.getWriter();
- out.write(json);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (out != null) {
- out.close();
- }
- }
- }
这个时候 @ResponseBody 就派上用场了, 只需要一个注解, 全部搞定
- $.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;
- }
前台 console 输出
- {
- "age": 35,
- "name": "韦德"
- }
总结
在网上看到很不错的流程图, 作为总结吧
来源: http://www.phperz.com/article/18/0309/356875.html