directory
The full code is here
Spring MVC has excellent support for the JSON data format, making it easy to return JSON data after configuration without using any annotations.
Spring supports JSON in three different ways, each of which is described below, with some preparatory work.
What should be added to the configuration file
- What packages should be added to the Maven configuration file In addition to the Spring MVC core packages, there are jSON-related dependencies
<?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 the 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>
<! -- configure SpringMVC package -->
<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>
<! -- Configure JSON package -->
<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>
Copy the code
- In addition to the view-related beans to be configured in the Spring configuration file, you also need to configure jSON-related beans
<?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/>
<! -- This must be added -->
<mvc:annotation-driven />
<! -- Bean related to view path -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<! Json-related beans -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="defaultViews">
<list>
<! -- Json view -->
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</list>
</property>
</bean>
</beans>
Copy the code
Create the model class
package com.learn.model;
public class User {
private String name;
private String id;
private String email;
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId(a) {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail(a) {
return email;
}
public void setEmail(String email) {
this.email = email; }}Copy the code
How to return JSON data
So before we go into the three ways, let’s create a 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 {}Copy the code
1, @responseBody,
Add the following code directly to the controller:
@RequestMapping(value = "/user/first")
@ResponseBody
public User getUserJSONInfo(a){
System.out.println("Request JSON data!!");
User user = new User();
user.setName("today");
user.setId("10086");
user.setEmail("[email protected]");
return user;
}
Copy the code
In the above code, the @responseBody annotation indicates that this method returns not a view, but a ResponseBody directly
This method returns an object of type User, but is automatically converted to a JSON object and returned to the front end during runtime
Running result:
2, use ResponseEntity
Add the following code to the controller:
@RequestMapping(value="/user/second")
public ResponseEntity<User> getUserJSONInfo2(a){
User user = new User();
user.setId("10086111");
user.setName("second");
user.setEmail("[email protected]");
return new ResponseEntity<User>(user, HttpStatus.OK);
}
Copy the code
3, httpServletResponse
This method is very simple, just set the return format to JSON format
Add the following code to the controller:
@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]\"}");
Copy the code
Running result:
4, use return multiple JSON objects
Code:
@RequestMapping(value = "/user/forth")
@ResponseBody
public Map<String, Object> getUserJSONInfo4(a){
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;
}
Copy the code
Running result: