Spring學習手冊 1:Spring MVC 返回JSON資料

EatherToo發表於2019-02-02

目錄

完整程式碼在這

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("123@gmail.com");
    return user;
}
複製程式碼

在上面的程式碼中,有 @ResponseBody註解,表明此方法返回的不是檢視,而直接是responseBody

這個方法返回的是User型別的物件,但是在執行過程中會被自動轉變成JSON物件返回給前端

執行結果:

Spring學習手冊 1:Spring MVC 返回JSON資料

2、使用 ResponseEntity

在控制器中加上如下程式碼:

@RequestMapping(value="/user/second")
public ResponseEntity<User> getUserJSONInfo2(){
    User user = new User();
    user.setId("10086111");
    user.setName("second");
    user.setEmail("second@gmail.com");
    return new ResponseEntity<User>(user, HttpStatus.OK);
}
複製程式碼

Spring學習手冊 1:Spring MVC 返回JSON資料

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\":\"third@gmail.com\"}");
複製程式碼

執行結果:

Spring學習手冊 1:Spring MVC 返回JSON資料

Spring學習手冊 1:Spring MVC 返回JSON資料

4、使用 返回多個JSON物件

程式碼:

@RequestMapping(value = "/user/forth")
@ResponseBody
public Map<String, Object> getUserJSONInfo4(){

    User user = new User();
    user.setName("forth");
    user.setId("10086");
    user.setEmail("forth@gmail.com");

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("users", user);
    map.put("info", "some info");
    map.put("time", "now");
    return map;
}
複製程式碼

執行結果:

Spring學習手冊 1:Spring MVC 返回JSON資料

相關文章