Spring Boot 2.x实战39 - Spring Web MVC 11 - Web MVC配置(HttpMessageConverter)

开发者福利!热门AI工具限时免费用 购周边即赠Coding Plan Lite,Claude Code、Cursor等20+工具畅享,效率翻倍! 阅读详情
3.5 HttpMessageConverter

在Spring MVC中请求(@RequestBodyRequestEntity等)和返回(@ResponsebodyResponseEntity等)都是通过HttpMessageConverter来实现数据转换的。

外部的请求数据通过HttpMessageConverter转换成Java对象,而Java对象又通过HttpMessageConverter转换成外部数据到返回中。在我们前面的例子中,web请求体中的Json数据通过MappingJackson2HttpMessageConverter转换成Java对象,而Java对象也通过MappingJackson2HttpMessageConverter转换成Json到返回体中。

HttpMessageConverter会根据请求或返回的内容类型(Content-Typeapplication/json)来选择对应的HttpMessageConverter对数据进行转换。

Spring MVC为我们自动注册了下列的HttpMessageConverter

  • ByteArrayHttpMessageConverter:二进制数组转换

  • StringHttpMessageConverter:字符串转换,支持的媒体类型:

  • ResourceHttpMessageConverterorg.springframework.core.io.Resource类型转换

  • SourceHttpMessageConverterjavax.xml.transform.Source类型准换

  • 各种Json库的HttpMessageConverter

    • MappingJackson2HttpMessageConverter:当jackson-databind jar包在类路径时注册,当前请求体和返回体都是用它来做数据转换的
    • MappingJackson2XmlHttpMessageConverter:当jackson-dataformat-xml jar包在类路径时注册
    • Jaxb2RootElementHttpMessageConverter:当jaxb-api jar包在类路径时注册
    • GsonHttpMessageConverter:当gson jar包在类路径时注册
    • JsonbHttpMessageConverter:当javax.json.bind-api jar包在类路径时注册

我们也定义一个HttpMessageConverter来演示它的功能。我们首先定义一个我们专门用来演示数据转换的类:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AnotherPerson {
    private Long id;
    private String name;
    private Integer age;
}

继承AbstractHttpMessageConverter(实现了HttpMessageConverter接口)抽象类来定制:

public class AnotherPersonHttpMessageConverter extends AbstractHttpMessageConverter<AnotherPerson> {

    public AnotherPersonHttpMessageConverter() {
        super(new MediaType("application","another-person", Charset.defaultCharset()));//1
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return AnotherPerson.class.isAssignableFrom(clazz); //2
    }

    @Override
    protected AnotherPerson readInternal(Class<? extends AnotherPerson> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        String body = StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset());
        String[] personStr = body.split("-");
        return new AnotherPerson(Long.valueOf(personStr[0]), personStr[1], Integer.valueOf(personStr[2])); //3
    }

    @Override
    protected void writeInternal(AnotherPerson anotherPerson, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        String out = "Hello:" + anotherPerson.getId() + "-" +
                anotherPerson.getName() + "-" +
                anotherPerson.getAge();
        StreamUtils.copy(out, Charset.defaultCharset(), outputMessage.getBody()); //4
    }
}
  1. 构造器中自定义我们自己的媒体类型application/another-person
  2. 当前HttpMessageConverter支持转换的类型是AnotherPerson类;
  3. 将请求体内的字符串6-foo-28转换成AnotherPerson对象;
  4. AnotherPerson对象转换成对应的字符串形式。

注册HttpMessageConverter的方式很多:

  • 直接定义Bean:

    @Bean
    HttpMessageConverter anotherPersonHttpMessageConverter(){
        return new AnotherPersonHttpMessageConverter();
    }
    
  • 定义HttpMessageConverters的Bean,这是Spring Boot为我们专门提供的,推荐使用

    @Bean
    HttpMessageConverters httpMessageConverters(){
        return new HttpMessageConverters(new AnotherPersonHttpMessageConverter());
    }
    
  • 重载WebMvcConfigurer的方法configureMessageConverters

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new AnotherPersonHttpMessageConverter());
    }
    

我们使用前两种注册HttpMessageConverter方式时,控制器:

@GetMapping("/converter")
public AnotherPerson converter(@RequestBody AnotherPerson person){
    return person;
}

使用第三种注册方式时,因Spring MVC默认使用MappingJackson2HttpMessageConverter来对请求体和返回体进行处理,我们需指定返回体的媒体类型:

@GetMapping(value = "/converter", produces = {"application/another-person"})
public AnotherPerson converter(@RequestBody AnotherPerson person){
    return person;
}

我们用Postman请求时候,要将请求头的Content-Type设置为application/another-person

在这里插入图片描述

我们请求的格式也是用“-”隔开:
在这里插入图片描述

新书推荐:

我的新书《从企业级开发到云原生微服务:Spring Boot 实战》已出版,内容涵盖了丰富Spring Boot开发的相关知识
购买地址:https://item.jd.com/12760084.html
在这里插入图片描述

主要包含目录有:

第一章 初识Spring Boot(快速领略Spring Boot的美丽)
第二章 开发必备工具(对常用开发工具进行介绍:包含IntelliJ IDEA、Gradle、Lombok、Docker等)
第三章 函数式编程
第四章 Spring 5.x基础(以Spring 5.2.x为基础)
第五章 深入Spring Boot(以Spring Boot 2.2.x为基础)
第六章 Spring Web MVC
第七章 数据访问(包含Spring Data JPA、Spring Data Elasticsearch和数据缓存)
第八章 安全控制(包含Spring Security和OAuth2)
第九章 响应式编程(包含Project Reactor、Spring WebFlux、Reactive NoSQL、R2DBC、Reactive Spring Security)
第十章 事件驱动(包含JMS、RabbitMQ、Kafka、Websocket、RSocket)
第11章 系统集成和屁股里(包含Spring Integration和Spring Batch)
第12章 Spring Cloud与微服务
第13章 Kubernetes与微服务(包含Kubernetes、Helm、Jenkins、Istio)
多谢大家支持。

Springboot2 configureMessageConverters自定义消息转换器 实现全局http请求Long类型转换为String类型 1.自定义WebMvcConfig实现WebMvcConfigurer并复写configureMessageConverters方法,添加自定义转换器 @Configuration public class WebMvcConfig implements WebMvcConfigurer { /** * 添加自定义转换器 * @param converters */ @Override public 阅读详情

相关推荐

SpringBoot2.x系列教程(十八)HttpMessageConverter实战及经验

在篇文章中介绍了自定义HttpMessageConverter的使用,其中我们通过实现WebMvcConfigurer接口来完成自定义HttpMessageConverter并向spring容器中添加的操作。本篇文章我们就通过集成fastjson这个实例,来汇总一下将HttpMessageConverter添加到容器中的集中操作。 通过@Configuration添加 我们已经知道,通过@Conf...

程序新视界 2643

spring boot学习(7)— 自定义中的 HttpMessageConverter

在我们开发自己的应用时,有时候,我们可能需要自定义一些自己的数据格式来传输,这时,自定义的数据传输和类的实例之间进行转化就需要统一起来了, Spring MVC 中的 HttpMessageConverter 就派上用场了。 HttpMessageConverter 的声明: public interface HttpMessageConverter<T> { /** ...

weixin_34099526的博客 526

深入理解Spring中的HttpMessageConverters

是一个方便的管理HTTP消息转换器的工具类。它可以作为一个Bean注册到Spring应用中。

m0_62153576的博客 690

SpringBoot 项目 @EnableWebMvc 注解应用的总结

spring-boot+spring mvc 的项目中,有我们需要自己配置一些项目的设置,就会涉及到三个类(@EnableWebMvcWebMvcConfigurationSupport和WebMvcConfigurationAdapter),那么,他们之间有什么关系呢?  首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMv...

曾舜尧的专栏 2052

org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

启动项目的时候报错: java.lang.ClassNotFoundException:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter 原因:jackson包版本过低,因在2.0以上

Cyl_1991的博客 1452

spring mvc HttpMessageConverter 消息转换器

如果默认内置的converter不能满足要求,可以进行自定义converter。如请求的body存在转码或加密,或有固定头信息,不是标准的json格式,则可以继承MappingJackson2HttpMessageConverter 类,然后重写对应的read和write方法。自定义的converter可以通过WebMvcConfigurer加载到容器中。@Override也可以通过将自定义的MessageConverter注册未一个bean来让容器自动加载。

sinat_16493273的博客 875

SpringMVC实现WebMvcConfigurer配置自定义消息转换器或第三方转换器不生效

由于converters是HttpMessageConverter的列表 而新add的消息转换器位于列表的最后 所以可能不生效 可以把它插入列表头 使用add(0,converter) @Configuration public class MVCConfig implements WebMvcConfigurer { @Override public void extendMessageConverters(List<HttpMessageConverter<?>&gt

weixin_45754452的博客 1601

HttpMessageConverter 消息转换器

HttpMessageConverterSpringMVC中提供的一个策略接口,它是一个消息转换器类,Spring Mvc中就是由HttpMessageConverter负责转换HTTP的请求和响应。默认情况下,Spring Boot 会自动加载如下消息类型转换器:StringHttpMessageConverter:负责读取字符串格式的数据和写出二进制格式的数据(当返回值是或者接受值是String类型时,是由这个处理)

Huangjiazhen711的博客 7141

Spring MVC系列(9)-HttpMessageConverter报文转换流程源码解析

HttpMessageConverters类 HttpMessageConverters是org.springframework.boot.autoconfigure.http下的一个类,是 Spring Boot提供的管理应用程序中使用HttpMessageConverter的Bean。 提供一种方便的方法来添加和配置额外的HttpMessageConverterWeb 应用程序。如果需要,可以使用特定的HttpMessageConverters注册此 bean 的实例,否则将使用默认转换器。 Htt

记录知识、锤炼自我 2733

Spring MVC 增加自定义HttpMessageConverter

 前提: spring版本:        &lt;spring.version&gt;4.3.22.RELEASE&lt;/spring.version&gt; JDK1.8 代码说明: 由于使用了一个SVN库,因此将代码导出来吧,可以共大家参考。 关注点: 代码zip压缩包。   实操步骤: 按照官方文档增加【org.springframework.web.servlet.mv...

qq_30801257的博客 1208

SpringBoot---web-->>自定义MessageConverter

自定义MessageConverter 之前的学习中,方法加一个@ResponseBody注解就能把返回的对象转换为json或xml格式响应在页面上,通过获取请求头信息的方式或者开启参数内容协商功能实现获取指定类型的数据。但是能用的都是规定好的,假如现在需要把浏览器发送的请求返回的数据返回为xml格式,参数请求返回的数据为json,app返回的数据为aaaa自定类型,就要自己定义一个MessageConverter 自定义Converter,就是定制化配置SpringBoot底层,刚学springB

wowo 727

springboot配置fastjson后端往前端传输格式化

   import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.http.HttpMessageConverters;...

NMSL6666的博客 439

2.5配置自定义HttpMessageConverters

当我们创建RESTful的web数据服务时,我们声明了controllers,repositories和写了注释。但是,无论我们处理任何对象,我们最终都要将对象转换为HTTP的数据,以输出流输出。然而,在我们的应用场景之下,Spring Boot自动配置HttpMessageConverters去转换我们的实体类到JSON,这中间使用了Jackson包。最后以JSON格式的数据响应一个HTTP的请求。 HttpMessageConverters的目的转换不同类型的对象到它们请求HTTP的输出流格式。一..

owen_william的博客 1764

HttpMessageConverter(消息转换器 )和@responsebody使用

@responsebody表示该方法的返回结果直接写入HTTP response body中 一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。 Spring

Tomorrow never comes 1万+

SpringMVC消息转换器HttpMessageConverter

Http数据转换的原理 当一个HTTP请求到达时是一个InputStream,通过HttpMessageConverter转换为java对象,从而进行参数接收。 当对一个HTTP请求进行响应时,我们首先输出的是一个java对象,然后由HttpMessageConverter转换为OutputStream输出。 当我们在Spring Boot应用中集成了jackson的类库之后,如下的一些HttpMessageConverter将会被加载: 实现类 功能说明 StringHttpMessag

2184

Spring Boot返回前端Long型丢失精度

spring cloud alibaba项目中long类型数据返回前端最后两位变成00,参考了很多博客最后这篇对此项目有效果: 解决办法之一就是让Javascript把数字当成字符串进行处理,对Javascript来说如果不进行运算,数字和字符串处理起来没有什么区别。但如果需要进行运算,只能采用其他方法,例如JavaScript的一些开源库 bignum、bigint等支持长整型的处理。在我们这个场景里不需要进行运算,且Java进行JSON处理的时候是能够正确处理long型的,所以只需要将数字转化..

zhangkang65的专栏 4450

spring-boot2.x,使用EnableWebMvc注解导致的自定义HttpMessageConverters不可用

@EnableWebMvc注解可能导致自定义HttpMessageConverters不可用

gaoshan12345678910的博客 872

SpringMVC,SpringBoot统一响应结果返回值为String的异常处理原理分析

【代码】29. SpringMVC,SpringBoot统一响应结果返回值为String的异常处理原理分析。

JavaMyDream的博客 2494

WebMvcConfigurer配置Converters转换器,//将Long转为string 解决id过大 js只显示16位的问题,超出变0

public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = jackso...

qq_42962779的博客 690
上一篇: 基于K8s、Strimzi的Kafka Connect实战
下一篇: Spring Boot 2.x实战40 - Spring Web MVC 12 - Web MVC配置(控制器方法参数和返回值处理设置-使用HandlerMethodArgumentResolver)
汪云飞记录本
博客等级 码龄20年 123粉丝 165原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值