Spring學習手冊 1:Spring MVC 返回JSON數據

目錄php

完整代碼在這html

Spring MVC對JSON數據格式的支持很是好,配置完成後什麼都不用管靠註解就能夠輕鬆返回JSON格式的數據。前端

Spring 對JSON的支持有三種方式,下面會一一介紹,在此以前先是一些準備工做。java

1、配置文件應該添加什麼東西

  • 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>
複製代碼

2、建立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;
    }
}
複製代碼

3、返回JSON數據的方式

在講三種方式以前,先建立一個Controllerweb

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 {

}
複製代碼

一、@ResponseBody方式、

直接在控制器內加上下面的代碼:spring

@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註解,代表此方法返回的不是視圖,而直接是responseBodyapache

這個方法返回的是User類型的對象,可是在運行過程當中會被自動轉變成JSON對象返回給前端json

運行結果:api

二、使用 ResponseEntity

在控制器中加上以下代碼:spring-mvc

@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);
}
複製代碼

三、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\"}");
複製代碼

運行結果:

四、使用 返回多個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;
}
複製代碼

運行結果:

相關文章
相關標籤/搜索