springboot自定义消息转换器HttpMessageConverter
在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换,底层这种灵活的消息转换机制就是利用HttpMessageConverter来实现的,Spring内置了很多HttpMessageConverter,比如MappingJackson2HttpMessageConverter,StringHttpMessageConverter等,下面我们来自定义自己的消息转换器来满足自己特定的需求,有两种方式:1、使用spring或者第三方提供的现成的HttpMessageConverter,2、自己重写一个HttpMessageConverter。
配置使用FastJson插件返回json数据
在springboot项目里当我们在控制器类上加上@RestController注解或者其内的方法上加入@ResponseBody注解后,默认会使用jackson插件来返回json数据,下面我们利用fastjson为我们提供的FastJsonHttpMessageConverter来返回json数据。
首先要引入fastjson的依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
接下来通过实现WebMvcConfigurer接口来配置FastJsonHttpMessageConverter,springboot2.0版本以后推荐使用这种方式来进行web配置,这样不会覆盖掉springboot的一些默认配置。配置类如下:
package com.example.demo; import java.util.List; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; @Configuration
public class MyWebmvcConfiguration implements WebMvcConfigurer{ @Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fjc = new FastJsonHttpMessageConverter();
FastJsonConfig fj = new FastJsonConfig();
fj.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
fjc.setFastJsonConfig(fj);
converters.add(fjc);
} }
fastJson配置实体调用setSerializerFeatures方法可以配置多个过滤方式,常用的如下:
2、WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
3、DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
4、WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
5、WriteMapNullValue:是否输出值为null的字段,默认为false。
package com.example.demo; import java.util.ArrayList;
import java.util.List; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; @RestController
public class UserController { @RequestMapping(value="/get",method=RequestMethod.GET)
public Object getList(){
List<UserEntity> list= new ArrayList<UserEntity>();
UserEntity u1 = new UserEntity(null, "shanghai");
list.add(u1);
return list;
} }
package com.example.demo; import lombok.AllArgsConstructor;
import lombok.Data; @Data
@AllArgsConstructor
public class UserEntity {
private String name;
private String address; }
设置端口为8888,启动项目访问http://localhost:8888/get,我们代码中没有配置WriteMapNullValue,所以如果返回结果中有null值则不显示,结果如下:

我们注释掉fastjson配置,重新启动项目并访问,从结果可以看出我们配置的消息转换器起作用了。

重写HttpMessageConverter
接下来我们继承AbstractHttpMessageConverter来实现一个自己的消息转换器,示例如下:
package com.example.demo; import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils; import java.io.IOException;
import java.nio.charset.Charset; public class MyMessageConverter extends AbstractHttpMessageConverter<UserEntity> { public MyMessageConverter() {
// 新建一个我们自定义的媒体类型application/xxx-junlin
super(new MediaType("application", "xxx-junlin", Charset.forName("UTF-8")));
} @Override
protected boolean supports(Class<?> clazz) {
// 表明只处理UserEntity类型的参数。
return UserEntity.class.isAssignableFrom(clazz);
} /**
* 重写readlntenal 方法,处理请求的数据。代码表明我们处理由“-”隔开的数据,并转成 UserEntity类型的对象。
*/
@Override
protected UserEntity readInternal(Class<? extends UserEntity> clazz,
HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
String[] tempArr = temp.split("-"); return new UserEntity(tempArr[0],tempArr[1]);
} /**
* 重写writeInternal ,处理如何输出数据到response。
*/
@Override
protected void writeInternal(UserEntity userEntity,
HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
String out = "hello: " + userEntity.getName() + "-" + userEntity.getAddress();
outputMessage.getBody().write(out.getBytes());
}
}
将自定义的消息转换器加入到springmvc容器中,以便被使用。
package com.example.demo; import java.util.List; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; @Configuration
public class MyWebmvcConfiguration implements WebMvcConfigurer{ @Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fjc = new FastJsonHttpMessageConverter();
FastJsonConfig fj = new FastJsonConfig();
fj.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
fjc.setFastJsonConfig(fj);
converters.add(fjc);
converters.add(converter());
}
@Bean
public MyMessageConverter converter() {
return new MyMessageConverter();
} }
UserController中加入测试的代码
package com.example.demo; import java.util.ArrayList;
import java.util.List; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; @RestController
public class UserController { @RequestMapping(value="/get",method=RequestMethod.GET)
public Object getList(){
List<UserEntity> list= new ArrayList<UserEntity>();
UserEntity u1 = new UserEntity(null, "shanghai");
list.add(u1);
return list;
} @RequestMapping(method = RequestMethod.POST, value = "/convert")
public @ResponseBody UserEntity converter(@RequestBody UserEntity user) {
return user;
}
}
启动项目,使用postman来测试,从响应来看我们的消息转换器已经起作用了,如下:



springboot自定义消息转换器HttpMessageConverter的更多相关文章
- springboot自定义消息转换器HttpMessageConverter Spring Boot - 使用Gson替换Jackson
Jackson一直是springframework默认的json库,从4.1开始,springframework支持通过配置GsonHttpMessageConverter的方式使用Gson. 在典型 ...
- SpringBoot 消息转换器 HttpMessageConverter
1.简介: Spring在处理请求时,由合适的消息转换器将请求报文绑定为方法中的形参对象,在这里,同一个对象就有可能出现多种不同的消息形式,比如json和xml.同样,当响应请求时,方法的返回值也同样 ...
- 【Spring学习笔记-MVC-1.3】消息转换器HttpMessageConverter
作者:ssslinppp 参考链接: SpringMVC源码剖析(五)-消息转换器HttpMessageConverter: http://my.oschina.net/lichhao/b ...
- SpringBoot添加自定义消息转换器
首先我们需要明白一个概念:springboot中很多配置都是使用了条件注解进行判断一个配置或者引入的类是否在容器中存在,如果存在会如何,如果不存在会如何. 也就是说,有些配置会在springboot中 ...
- JavaEE开发之SpringMVC中的自定义消息转换器与文件上传
上篇博客我们详细的聊了<JavaEE开发之SpringMVC中的静态资源映射及服务器推送技术>,本篇博客依然是JavaEE开发中的内容,我们就来聊一下SpringMVC中的自定义消息转发器 ...
- SpringMVC——消息转换器HttpMessageConverter(转)
文章转自http://blog.csdn.net/cq1982/article/details/44101293 概述 在SpringMVC中,可以使用@RequestBody和@ResponseBo ...
- SpringMVC源码剖析(五)-消息转换器HttpMessageConverter
原文链接:https://my.oschina.net/lichhao/blog/172562 #概述 在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分 ...
- SpringMVC源码剖析5:消息转换器HttpMessageConverter与@ResponseBody注解
转自 SpringMVC关于json.xml自动转换的原理研究[附带源码分析] 本系列文章首发于我的个人博客:https://h2pl.github.io/ 欢迎阅览我的CSDN专栏:Spring源码 ...
- springboot/springmvc转换器
常用的转换器 String转Date转换器(用于接受日期参数自动转换成Date类型便于后台数据处理) /** * 全局handler前日期统一处理 * @author zhanghang * @dat ...
随机推荐
- VM虚拟机占内存非常大
我发现每次打开虚拟机占用内存非常大,经常会卡死,后来上网找原因,发现内存设置的问题,所以我就修改了虚拟机的内存,网上说如果是win7,内存设置需要1-2G,如果是xp,512M就够了. 经测试,内存还 ...
- 终端直接执行py文件,不需要python命令
然后给脚本文件运行权限,方法(1)chmod +x ./*.py方法(2)chmod 755 ./*.py (777也无所谓啦) 这个命令不去调整,会出现permission denied的错误终端直 ...
- ni_set()函数的使用 以及 post_max_size,upload_max_filesize的修改方法
Apache服务器处理: ini_set('display_errors', 'Off');ini_set('memory_limit', -1); //-1 / 10240Mini_set(&quo ...
- javascript的面向对象思想知识要点
获取数据类型 typeof undefined:访问某个不存在的或未经赋值的变量时就会得到一个 undefined,用typeof 获取类型,得到的也是undefined;null:它不能通过java ...
- 一些你需要知道的Python代码技巧
被人工智能捧红的 Python 已是一种发展完善且非常多样化的语言,其中肯定有一些你尚未发现的功能.本文或许能够让你学到一些新技巧. Python 是世界上最流行.热门的编程语言之一,原因很多,比 ...
- 基于Linux的Samba开源共享解决方案测试(二)
单NAS网关50Mb码率视音频文件的稳定读测试结果如下: 50Mb/s负载性能记录 NAS网关资源占用 稳定读 稳定读 CPU空闲 内存空闲 网卡占用 13个稳定流 96.70% 10G 104MB/ ...
- solr联合多个字段进行检索(multivalued和copyfield的使用)
在实际工作中不仅仅对索引中的单个字段进行搜索.需要进行综合查询. 比如book表中有id,name(标题),price,summary(摘要),content(内容),我们要找一本书的时候,查询关键字 ...
- MySQL数据库索引(上)
上一篇回顾: 1.数据页由七部分组成,包括File Header(描述页的信息).Page Header(描述数据的信息).Infimum + Supremum(页中的虚拟数据最大值和最小值).Use ...
- 线程使用方法 锁(lock,Rlock),信号了(Semaphore),事件(Event),条件(Ccndition),定时器(timer)
2线程的使用方法 (1)锁机制 递归锁 RLock() 可以有无止尽的锁,但是会有一把万能钥匙 互斥锁: Lock() ...
- ajax 方法的使用以及方法中各参数的含义
由于近来经常在项目中使用 ajax 这个函数,在工作之余自己查找了相关的资料,并总结了 ajax 方法的使用,以及方法中各个参数的含义,供大家学习参考使用 type: 要求为String类型的参数,请 ...