栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

详解自定义SpringMVC的Http信息转换器的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解自定义SpringMVC的Http信息转换器的使用

在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换,底层这种灵活的消息转换机制。使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上。

HttpInputMessage

这个类是SpringMVC内部对一次Http请求报文的抽象,在HttpMessageConverter的read()方法中,有一个HttpInputMessage的形参,它正是SpringMVC的消息转换器所作用的受体“请求消息”的内部抽象,消息转换器从“请求消息”中按照规则提取消息,转换为方法形参中声明的对象。

package org.springframework.http;

import java.io.IOException;
import java.io.InputStream;

public interface HttpInputMessage extends HttpMessage {

  InputStream getBody() throws IOException;

}

HttpOutputMessage

在HttpMessageConverter的write()方法中,有一个HttpOutputMessage的形参,它正是SpringMVC的消息转换器所作用的受体“响应消息”的内部抽象,消息转换器将“响应消息”按照一定的规则写到响应报文中。

package org.springframework.http;

import java.io.IOException;
import java.io.OutputStream;

public interface HttpOutputMessage extends HttpMessage {

  OutputStream getBody() throws IOException;

}

HttpMessageConverter



package org.springframework.http.converter;

import java.io.IOException;
import java.util.List;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;


public interface HttpMessageConverter {


  boolean canRead(Class clazz, MediaType mediaType);

  boolean canWrite(Class clazz, MediaType mediaType);

  List getSupportedMediaTypes();


  T read(Class clazz, HttpInputMessage inputMessage)
      throws IOException, HttpMessageNotReadableException;


  void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
      throws IOException, HttpMessageNotWritableException;

}

HttpMessageConverter 接口提供了5个方法:

  1. canRead :判断该转换器是否能将请求内容转换成Java对象
  2. canWrite :判断该转换器是否可以将Java对象转换成返回内容
  3. getSupportedMediaTypes :获得该转换器支持的MediaType类型
  4. read :读取请求内容并转换成Java对象
  5. write :将Java对象转换后写入返回内容

其中 read 和 write 方法的参数分别有有 HttpInputMessage 和 HttpOutputMessage 对象,这两个对象分别代表着一次Http通讯中的请求和响应部分,可以通过 getBody 方法获得对应的输入流和输出流。

当前Spring中已经默认提供了相当多的转换器,分别有:

名称 作用 读支持MediaType 写支持MediaType
ByteArrayHttpMessageConverter 数据与字节数组的相互转换 / application/octet-stream
StringHttpMessageConverter 数据与String类型的相互转换 text @Override public boolean canRead(Class clazz, MediaType mediaType) { if (mediaType == null) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.includes(mediaType)) { return true; } } return false; } @Override public boolean canWrite(Class clazz, MediaType mediaType) { if (mediaType == null || MediaType.ALL.equals(mediaType)) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.includes(mediaType)) { return true; } } return false; } @Override public List getSupportedMediaTypes() { return supportedMediaTypes; } @Override public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return mapper.readValue(inputMessage.getBody(), clazz); } @Override public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { mapper.writevalue(outputMessage.getBody(), o); } }

自定义MappingJackson2HttpMessage

从 MappingJackson2HttpMessageConverter 的父类 AbstractHttpMessageConverter 中的 write 方法可以看出,该方法通过 writeInternal 方法向返回结果的输出流中写入数据,所以只需要重写该方法即可:

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
  return new MappingJackson2HttpMessageConverter() {
    //重写writeInternal方法,在返回内容前首先进行加密
    @Override
    protected void writeInternal(Object object,
     HttpOutputMessage outputMessage) throws IOException,
 HttpMessageNotWritableException {
      //使用Jackson的ObjectMapper将Java对象转换成Json String
      ObjectMapper mapper = new ObjectMapper();
      String json = mapper.writevalueAsString(object);
      LOGGER.error(json);
      //加密
      String result = json + "加密了!";
      LOGGER.error(result);
      //输出
      outputMessage.getBody().write(result.getBytes());
    }
  };
}
 

在这之后还需要将这个自定义的转换器配置到Spring中,这里通过重写 WebMvcConfigurer 中的 configureMessageConverters 方法添加自定义转换器:

//添加自定义转换器
@Override
public void configureMessageConverters(List> converters) {
  converters.add(mappingJackson2HttpMessageConverter());
  super.configureMessageConverters(converters);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号