Spring学习手册 1:Spring MVC 返回JSON数据
Spring学习手册 1:Spring MVC 返回JSON数据
Spring MVC对JSON数据格式的支持非常好,配置完成后什么都不用管靠注解就可以轻松返回JSON格式的数据。
Spring 对JSON的支持有三种方式,下面会一一介绍,在此之前先是一些准备工作。
一、配置文件应该添加什么东西
- Maven配置文件应该添加哪些包 除了Spring MVC的核心包之外,还要加上JSON相关的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.learn.springmvc</groupId>
<artifactId>SpringMVCJSONDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVCJSONDemo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--配置SpringMVC包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<!--配置JSON包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCJSONDemo</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
复制代码
- Spring配置文件中除了和视图相关的bean要配置外,还需要配置和JSON有关的bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.learn.Controller com.learn.model"/>
<context:annotation-config/>
<!--这个一定要加-->
<mvc:annotation-driven />
<!--和视图路径有关的bean-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!--和json有关的bean-->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="defaultViews">
<list>
<!-- Json视图 -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</list>
</property>
</bean>
</beans>
复制代码
二、创建model类
package com.learn.model;
public class User {
private String name;
private String id;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
复制代码
三、返回JSON数据的方式
在讲三种方式之前,先创建一个Controller
package com.learn.Controller;
import com.learn.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RequestMapping("json")
@Controller
public class UserController {
}
复制代码
1、@ResponseBody方式、
直接在控制器内加上下面的代码:
@RequestMapping(value = "/user/first")
@ResponseBody
public User getUserJSONInfo(){
System.out.println("请求JSON数据!!!");
User user = new User();
user.setName("today");
user.setId("10086");
user.setEmail("[email protected]");
return user;
}
复制代码
在上面的代码中,有 @ResponseBody注解,表明此方法返回的不是视图,而直接是responseBody
这个方法返回的是User类型的对象,但是在运行过程中会被自动转变成JSON对象返回给前端
运行结果:
2、使用 ResponseEntity
在控制器中加上如下代码:
@RequestMapping(value="/user/second")
public ResponseEntity<User> getUserJSONInfo2(){
User user = new User();
user.setId("10086111");
user.setName("second");
user.setEmail("[email protected]");
return new ResponseEntity<User>(user, HttpStatus.OK);
}
复制代码
3、httpServletResponse
这个方法很简单,就是自己把返回格式设成json格式就可以了
在控制器中加入如下代码:
@RequestMapping(value = "/user/third")
public void getUserJSONInfo3(HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.getWriter().println("{\"name\":\"third\",\"id\":\"10086\",\"email\":\"[email protected]\"}");
复制代码
运行结果:
4、使用 返回多个JSON对象
代码:
@RequestMapping(value = "/user/forth")
@ResponseBody
public Map<String, Object> getUserJSONInfo4(){
User user = new User();
user.setName("forth");
user.setId("10086");
user.setEmail("[email protected]");
Map<String, Object> map = new HashMap<String, Object>();
map.put("users", user);
map.put("info", "some info");
map.put("time", "now");
return map;
}
复制代码
运行结果: