SpringMVC返回JSON以及进阶

开发环境

  1. IDEA 2017
  2. JDK 1.8
  3. Spring 4.2.2.RELEASE
  4. Jackson 2.8.5

项目结构

└─main
    ├─java
    │  └─com
    │      └─smart
    │          ├─controller
    │          │      JSONController.java
    │          │
    │          └─domain
    │                  User.java
    │
    ├─resources
    │      smart-context.xml
    │
    └─webapp
        └─WEB-INF
                web.xml

因为是一个小 demo,所以代码尽量简单,只有一个 Controller 和 Domain 对象

依赖

pom.xml

<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.smart</groupId>
    <artifactId>chapter2</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>

        <spring.version>4.2.2.RELEASE</spring.version>
        <jackson.version>2.8.5</jackson.version>
        <tomcat7-maven-plugin>2.2</tomcat7-maven-plugin>
    </properties>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- JSON -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>${tomcat7-maven-plugin}</version>
                <configuration>
                    <path>/${project.artifactId}</path>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

只需要 SpringMVC 和 Jackson 依赖即可

Domain

package com.smart.domain;

public class User {

    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Controller

package com.smart.controller;

import com.smart.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class JSONController {

    @RequestMapping("/testJavaBean")
    @ResponseBody
    public User test(@RequestParam("name") String name) {
        User user = new User();
        user.setUserName(name);
        user.setPassword("123456");
        return user;
    }


    @RequestMapping("/testMap")
    @ResponseBody
    public Map test2(@RequestParam("name") String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("test", 123);
        map.put("array", new String[]{"a", "b", "c"});
        return map;
    }
}

别忘了给 Controller 的方法添加上 @ResponseBody 注解,这样才能返回 JSON

ApplicationContext.xml

smart-context.xml

<?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: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/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.smart.controller"/>

    <mvc:annotation-driven/>

</beans>

Spring 的配置文件也是很简单,关键在于要加上 <mvc:annotation-driven/>

web.xml

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:smart-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>smart</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:smart-context.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>smart</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

web.xml 指定 ApplicationContext 的文件位置即可

运行结果

URL http://localhost:8080/chapter2/testJavaBean?name=我是中文

进阶

一般在真实开发的时候,JSON 数据一般是这样的

  • 请求成功的时
{
    "code": 200,
    "data": {
        "userId": 1,
        "userName": "Admin",
        "credits": 160,
        "lastIp": "0:0:0:0:0:0:0:1",
        "lastVisit": 1514968628552
    }
}
  • 请求失败时
{
    "code": 404,
    "message": "账号或密码错误"
}

从上面可以看到,服务器传回来的 JSON 格式是这样

{
    "code": xx,
    "message": xx,
    "data": xxx
}

而且,如果 JSON 数据中的值为 null 的话,就不传回来。对于这样的需求要怎么实现呢?

APIResult

首先按照服务器的 JSON 格式,定义一个 JavaBean,至于 data 部分用 Object 表示

package com.smart.domain;

import com.smart.constant.ApiConstant;

public class APIResult {

    private int code;
    private String message;
    private Object data;

    public static APIResult createOk(Object data) {
        return createWithCodeAndData(ApiConstant.Code.OK, null, data);
    }

    public static APIResult createOKMessage(String message) {
        APIResult result = new APIResult();
        result.setCode(ApiConstant.Code.OK);
        result.setMessage(message);
        return result;
    }

    public static APIResult createNg(String message) {
        return createWithCodeAndData(ApiConstant.Code.NG, message, null);
    }

    private static APIResult createWithCodeAndData(int code, String message, Object data) {
        APIResult result = new APIResult();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        return result;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

对于 null 字段不显示的需求,只需要在 ApplicationContext 配置文件定义即可。注意了,这个定义是全局生效的

<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
    <property name="serializationInclusion" value="NON_NULL"/>
</bean>

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper" />
            <property name="prettyPrint" value="true"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

最后就是修改一下 Controller 的代码,使用 APIResult 将数据包装起来

package com.smart.controller;

import com.smart.domain.APIResult;
import com.smart.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class JSONController {

    @RequestMapping("/testJavaBean")
    @ResponseBody
    public APIResult test(@RequestParam("name") String name) {
        User user = new User();
        user.setUserName(name);
        user.setPassword("123456");
        return APIResult.createOk(user);
    }


    @RequestMapping("/testMap")
    @ResponseBody
    public APIResult test2(@RequestParam("name") String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("test", 123);
        map.put("array", new String[]{"a", "b", "c"});
        return APIResult.createOk(map);
    }

    @RequestMapping("/testNg")
    @ResponseBody
    public APIResult testNg() {
        return APIResult.createNg("用户名或密码错误");
    }
}

URL: http://localhost:8080/chapter2/testNg

返回

{
    "code": 404,
    "message": "用户名或密码错误"
}

URL http://localhost:8080/chapter2/testMap?name=Admin

返回

{
    "code": 200,
    "data": {
        "test": 123,
        "array": [
            "a",
            "b",
            "c"
        ],
        "name": "Admin"
    }
}

URL http://localhost:8080/chapter2/testJavaBean?name=Admin

返回

{
    "code": 200,
    "data": {
        "userId": 0,
        "userName": "Admin",
        "password": "123456",
        "credits": 0
    }
}

对应SpringBoot框架的做法

如果是 SpringBoot 框架来开发的话,更简单了,不需要写一堆的配置文件。

Application

package com.smart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder applicationBuilder) {
        return applicationBuilder.sources(Application.class);
    }
}

只需要一个使用 @SpringBootApplication 讲某一个类注解为启动类即可,不需要写 ApplicationContext.xml 了

Controller

相反,Controller 只需要使用 @RestController 注解即可,可以将方法上的 @ResponseBody 注解去掉

package com.smart.controller;

import com.smart.domain.APIResult;
import com.smart.domain.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JSONController {

    @RequestMapping("/testJavaBean")
    public APIResult test(@RequestParam("name") String name) {
        User user = new User();
        user.setUserName(name);
        user.setPassword("123456");
        return APIResult.createOk(user);
    }

    @RequestMapping("/testNg")
    public APIResult testNg() {
        return APIResult.createNg("用户名或密码错误");
    }
}

对于JSON的格式要求:

  1. 去除 Null 字段
  2. 格式化打印

只需要在 src/main/resources/ 文件夹中创建一个 application.properties 文件,添加如下内容

spring.jackson.serialization.indent-output=true
spring.jackson.serialization-inclusion=non_null
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,585评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,923评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,314评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,346评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,718评论 3 291
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,828评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,020评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,758评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,486评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,722评论 2 251
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,196评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,546评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,211评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,132评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,916评论 0 200
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,904评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,758评论 2 274

推荐阅读更多精彩内容