SpringMVC 返回JSON、HttpMessageConverter 的使用

处理 JSON

点击进入maven的中央仓库下载所需Jackson jar包

• 1. 加入 jar 包: SpringMVC 返回JSON、HttpMessageConverter 的使用

• 2. 编写目标方法,使其返回 JSON 对应的对象或集合

• 3. 在方法上添加 @ResponseBody 注解

SpringMVC 返回JSON、HttpMessageConverter 的使用

HttpMessageConverter <T>

• HttpMessageConverter 是 Spring3.0 新添加的一个接 口,负责将请求信息转换为一个对象(类型为 T),将对象( 类型为 T)输出为响应信息 。

• HttpMessageConverter接口定义的方法:

– Boolean canRead(Class clazz,MediaType mediaType): 指定转换器可以读取的对象类型,即转换器是否可将请求信息转换为 clazz 类型的对象,同时指定支持 MIME 类型(text/html,applaiction/json等)

– Boolean canWrite(Class clazz,MediaType mediaType):指定转换器是否可将 clazz 类型的对象写到响应流中,响应流支持的媒体类型 在MediaType 中定义。

– LIst getSupportMediaTypes():该转换器支持的媒体类 型。

– T read(Class clazz,HttpInputMessage inputMessage): 将请求信息流转换为 T 类型的对象。

– void write(T t,MediaType contnetType,HttpOutputMessgae outputMessage):将T类型的对象写到响应流中,同时指定相应的媒体类型为 contentType。

SpringMVC 返回JSON、HttpMessageConverter 的使用

• DispatcherServlet 默认装配 RequestMappingHandlerAdapter ,而 RequestMappingHandlerAdapter 默认装配如下 HttpMessageConverter:

SpringMVC 返回JSON、HttpMessageConverter 的使用

• 加入 jackson jar 包后, RequestMappingHandlerAdapter 装配的 HttpMessageConverter 如下:

SpringMVC 返回JSON、HttpMessageConverter 的使用

 

HttpMessageConverter <T> 的实现类

SpringMVC 返回JSON、HttpMessageConverter 的使用

 使用 HttpMessageConverter<T>

• 使用 HttpMessageConverter 将请求信息转化并绑定到处理方法的入参中或将响应结果转为对应类型的响应信息,Spring 提供了两种途径:

– 使用 @RequestBody / @ResponseBody 对处理方法进行标注

– 使用 HttpEntity / ResponseEntity 作为处理方法的入参或返回值

• 当控制器处理方法使用到 @RequestBody/@ResponseBody 或 HttpEntity/ResponseEntity 时, Spring 首先根据请求头或响应头的 Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或 泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的 HttpMessageConverter 将报错。

• @RequestBody 和 @ResponseBody 可以不用成对出现。

@RequestBody、@ResponseBody 示例(实现文件上传并解析上传内容)

index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: 23369
  Date: 3/31/2019
  Time: 3:03 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>
</head>
<body>
<form action="testHttpMessageConverter" method="post" enctype="multipart/form-data">
    文件<input type="file" name="file"><br>
    描述<input type="text" name="desc"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>

TestHttpMessageConverter.class

package com.hello2;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
public class TestHttpMessageConverter {

    @ResponseBody
    @RequestMapping("testHttpMessageConverter")
    public String testHttpMessageConverter(@RequestBody String file){
        System.out.println(file);
        return "成功" + new Date() + "" +file;
    }

}

HttpEntity、ResponseEntity 示例(实现文件下载)

index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: 23369
  Date: 3/31/2019
  Time: 3:03 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
  <title>$Title$</title>
</head>
<body>

<a href="testResponseEntity">下载文件</a>
</body>
</html>

 TestHttpMessageConverter.class

package com.hello2;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Controller
public class TestHttpMessageConverter {


    @RequestMapping("testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession httpSession) throws IOException {

        String path = "/download/index-1.txt";

        byte[] body = null;
        ServletContext servletContext = httpSession.getServletContext();

        InputStream inputStream = servletContext.getResourceAsStream(path);
        body = new byte[inputStream.available()];
        inputStream.read(body);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition","attachment;filename=index-1.txt");

        HttpStatus httpStatus = HttpStatus.OK;

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body,httpHeaders,httpStatus);

        return responseEntity;
    }

}