1. 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1:http://www.cnblogs.com/ssslinppp/p/4528892.html 
  2. 【Spring学习笔记-MVC-4】返回Json数据-方式2:http://www.cnblogs.com/ssslinppp/p/4530002.html 
  3. 【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展:http://www.cnblogs.com/ssslinppp/p/4675495.html 
文章的内容主要如下:
  1. 方式1:讲解如果返回单个对象的json;==>使用@ResponseBody来实现;注解方式
  2. 方式2:讲解如果返回多个对象的json;==>使用MappingJacksonJsonView来实现;xml配置方式
  3. 方式1-扩展:讲解如果返回多个对象的json;==>使用@ResponseBody来实现;注解方式
个人认为,使用@ResponseBody方式来实现json数据的返回比较方便,推荐使用。

 

摘要


使用Spring MVC,实现json数据的返回。
主要步骤:
  1. 额外添加2个jar包;
  2. 使用 @ResponseBody声明返回值;
  3. 配置<mvc:annotation-driven />;==>需要引入:xmlns:mvc="http://www.springframework.org/schema/mvc";

@ResponseBody:

作用: 
该注解用于将Controller方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后(如:json格式),写入到Response对象的body数据区。 
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

<mvc:annotation-driven /> :

<mvc:annotation-driven /> 会自动注册
  1. DefaultAnnotationHandlerMapping
  2. AnnotationMethodHandlerAdapter 
两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。

 

需要的jar包


上面两个都是必须的。
 
 
 

项目结构


 
 

程序代码


Shop.java
  1. package com.ll.model;
  2. public class Shop {
  3. String name;
  4. String staffName[];
  5. public String getName() {
  6. return name;
  7. }
  8. public void setName(String name) {
  9. this.name = name;
  10. }
  11. public String[] getStaffName() {
  12. return staffName;
  13. }
  14. public void setStaffName(String[] staffName) {
  15. this.staffName = staffName;
  16. }
  17. }

JSONController.java

  1. package com.ll.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.PathVariable;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import com.ll.model.Shop;
  8. @Controller
  9. @RequestMapping("/kfc/brands")
  10. public class JSONController {
  11. @RequestMapping(value="{name}", method = RequestMethod.GET)
  12. public @ResponseBody Shop getShopInJSON(@PathVariable String name) {
  13. System.out.println("-----请求json数据--------");
  14. Shop shop = new Shop();
  15. shop.setName(name);
  16. shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
  17. return shop;
  18. }
  19. }

添加: @ResponseBody作为返回值。


web.xml

  1. <web-app id="WebApp_ID" version="2.4"
  2. xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  4. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  5. <display-name>Spring Web MVC Application</display-name>
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:applicationContext.xml</param-value>
  9. </context-param>
  10. <listener>
  11. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  12. </listener>
  13. <servlet>
  14. <servlet-name>mvc-dispatcher</servlet-name>
  15. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>mvc-dispatcher</servlet-name>
  20. <url-pattern>/rest/*</url-pattern>
  21. </servlet-mapping>
  22. </web-app>

 
mvc-dispatcher-servlet.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:context="http://www.springframework.org/schema/context"
  3. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  9. http://www.springframework.org/schema/mvc
  10. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  11. <context:component-scan base-package="com.ll.controller" />
  12. <mvc:annotation-driven />
  13. </beans>

开启:<mvc:annotation-driven />



applicationContext.xml


  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  14. <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
  15. <context:component-scan base-package="com.ll.model"/>
  16. </beans>

运行



参考网站


http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/ 

 
 
在《【Spring学习笔记-MVC-3】返回Json数据-方式1》中介绍了通过:
  1.  @ResponseBody声明返回值;
  2. 配置<mvc:annotation-driven />;
来返回json数据。效果如下:
  ==>
从上面的效果看,只能返回一个对象,不能返回多个对象,不能做到形如下图的返回结果,
存在局限性(可能可以返回多个,自己不知道如何实现)。
下面介绍的方式2,利用spring mvc返回json数据,可以实现同时返回多个对象的json数据
特别说明:
使用@ResponseBody可以实现同样的效果,实现同时返回多个对象的Json数据,而且使用@ ResponseBody方式更简洁。具体请参考《【Spring学习笔记-MVC-4】返回Json数据-方式1-kuozh》。
 

spring mvc实现json数据返回


具体步骤:
  1. 引入额外jar包:
  2. 使用bean视图解析器: org.springframework.web.servlet.view.BeanNameViewResolver;
  3. 使用 org.springframework.web.servlet.view.json.MappingJacksonJsonView配置需要返回的对象;
  4. 声明:<mvc:annotation-driven />;   经测试,不添加这个声明,将出错;
说明:
spring mvc默认的最常用的视图解析器为org.springframework.web.servlet.view.InternalResourceViewResolver

它的优先级默认是最低的,spring mvc还提供了许多其他类型的视图解析器,比如bean视图解析器

等,每个视图解析器的优先级都是可以手动设置的。在进行视图解析时,按照视图解析器优先级的顺序去解析视图,直到有视图解析器可以进行解析,解析过程就停止。
 
项目结构

 
 
配置web.xml

 

  1. <web-app id="WebApp_ID" version="2.4"
  2. xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  4. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  5. <display-name>Spring Web MVC Application</display-name>
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>classpath:applicationContext.xml</param-value>
  9. </context-param>
  10. <listener>
  11. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  12. </listener>
  13. <servlet>
  14. <servlet-name>mvc-dispatcher</servlet-name>
  15. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>mvc-dispatcher</servlet-name>
  20. <url-pattern>/rest/*</url-pattern>
  21. </servlet-mapping>
  22. </web-app>
 

 
配置mvc-dispatcher-servlet.xml

 

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:context="http://www.springframework.org/schema/context"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
  12. <context:component-scan base-package="com.ll.controller" />
  13. <mvc:annotation-driven />
  14. <!-- bean视图解析器 -->
  15. <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"
  16. p:order="10" />
  17. <!-- XMl及JSON视图解析器配置 -->
  18. <!-- <bean id="userListJson"
  19. class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"
  20. p:renderedAttributes="userList" /> -->
  21. <bean id="userListJson"
  22. class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
  23. <property name="renderedAttributes">
  24. <set>
  25. <value>userList</value>
  26. <value>School</value>
  27. <value>Work</value>
  28. </set>
  29. </property>
  30. </bean>
  31. </beans>

说明:
如果仅仅返回一个对象的json数据,可以使用简写配置:

 
JSONController.java

 
 
执行过程解析

1. 在mvc-dispatcher-servlet.xml文件中我们配置了bean视图解析器,并设置器优先级为10,
它的优先级是高于
2.逻辑视图返回值为:userListJson
它首先会被bean视图解析器解析,解析发现 userListJson对应的bean为:userListJson,其对应的视图为:MappingJacksonJsonView;

这样,便将userlist、School和work转化为json数据,并返回前台。
 
 
运行

浏览器: http://localhost:8080/SpringMVCQs/rest/kfc/brands/showUserListByJson 
 
完整程序

JSONController.java
  1. package com.ll.controller;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.ModelMap;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. import com.ll.model.Person;
  10. import com.ll.model.Shop;
  11. @Controller
  12. @RequestMapping("/kfc/brands")
  13. public class JSONController {
  14. @RequestMapping(value="/getShopInJson", method = RequestMethod.GET)
  15. public @ResponseBody Shop getShopInJSON() {
  16. System.out.println("-----请求json数据--------");
  17. Shop shop = new Shop();
  18. shop.setName("zhangsan");
  19. shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
  20. return shop;
  21. }
  22. @RequestMapping(value = "/showUserListByJson")
  23. public String showUserListInJson(ModelMap mm) {
  24. List<Person> userList = new ArrayList<Person>();
  25. Person user1 = new Person();
  26. user1.setUsername("tom");
  27. user1.setPasswd("汤姆");
  28. Person user2 = new Person();
  29. user2.setUsername("john");
  30. user2.setPasswd("约翰");
  31. userList.add(user1);
  32. userList.add(user2);
  33. mm.addAttribute("userList", userList);
  34. mm.addAttribute("School","SuZhou");
  35. mm.addAttribute("Work","YanFa");
  36. return "userListJson";
  37. }
  38. }