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("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数据

原文 

https://juejin.im/post/5c55a7e6e51d457ffd56fd74

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » Spring学习手册 1:Spring MVC 返回JSON数据

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址