spring,springBoot配置类型转化器Converter以及FastJsonHttpMessageConverter,StringHttpMessageConverter 使用
转载请注明出处:
https://i.cnblogs.com/posts/edit;postId=14045507
spring,spring boot 等框架项目通过@RequestBody,@ResponseBody 完成请求报文到响应对象及响应对象到响应报文的转换,其底层是通过
消息转换器完成消息之间的转换,包括格式转化,类型转化等。比如返回JSON数据或XML数据等。
spring 默认有很多消息类型转换器:
MappingJackson2XmlHttpMessageConverter 基于Jackson的XML转换器,能够将对象转换成XML格式的数据
MappingJackson2HttpMessageConverter 基于 Jackson 的JSON转换器,能够将对象转换成JSON格式的数据
GsonHttpMessageConverter 基于Gson的JSON转换器,能够将对象转换成JSON格式数据
对于系统中默认包含的转换器,只要我们在项目中加入转换器所依赖的JAR包,相关转换器就会被加载。
@RequestMapping(value="/json", produces={"application/json; charset=UTF-8"})
使用@RequestMapping设置的路径设置为 value属性的值,此外另外设置一个属性 produces,这个属性接受一个字符串数组。接受的数据类型是 media type。上面这个例子就是标明这个方法的返回结果要转换成UTF-8编码的JSON数据。
SpringMVC在项目初始化时,会去扫描系统中的JAR包,然后根据扫描到的JAR包设置默认的转换类型,大概的扫描过程是:
1)检查系统中是否存在jackson-xml的JAR包,如果存在,就将数据转换类型列表中设置XML类型,以及其对应的转换器
2)检查系统中是否存在jackson-json的JAR包,如果存在,就在数据转换类型列表中设置JSON类型,以及其对应的转换器
因为是先检测的XML,因此XML排在JSON前面,如果系统两者的JAR包都存在,那么默认情况下数据会被转换成XML格式
@RequestMapping(value="/xml", produces={"application/xml; charset=UTF-8"})
@ResponseBody
使用以上注解,则将会响应转换为XML 数据格式。
我们也可以在项目中使用指定的消息类型转换器,FastJson 封装了对应的类型转换器,只要在项目中引用fastJson对应的依赖配置;
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
通过实现 WebMvcConfigurer 接口来配置指定的消息类型转换器,
WebMvcConfigurer接口其实是spring的一种内部配置方式,采用java Bean的形式代替传统的xml配置形式,可以自定义一些Handler,Interceptor,ViewResolver, MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer 接口;
springboot2.0版本以后推荐使用这种方式来进行web配置,这样不会覆盖掉springboot的一些默认配置。配置类如下:
package com.lf.mp.test;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class CustomHttpMessageConverter implements WebMvcConfigurer {
/**
* 自定义使用FastJsonHttpMessageConverter
*
* @return
*/
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.QuoteFieldNames,
SerializerFeature.WriteMapNullValue,//保留空的字段
SerializerFeature.WriteNullListAsEmpty,//List null-> []
SerializerFeature.WriteDateUseDateFormat,// 日期格式化
SerializerFeature.WriteNullStringAsEmpty);//String null -> ""
List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
mediaTypeList.add(MediaType.APPLICATION_JSON);
fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypeList);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
return fastJsonHttpMessageConverter;
}
/**
* 在RsponseBody注解下,Spring处理返回值为String时会用到StringHttpMessageConverter,我们只需要在配置文件中设置好他的编译编码就ok了
*
* @return
*/
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter httpMessageConverter = new StringHttpMessageConverter();
httpMessageConverter.setDefaultCharset(Charset.defaultCharset());
return httpMessageConverter;
}
//保证StringHttpMessageConverter在FastJsonHttpMessageConverter前被调用
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//converters.removeIf(t -> t instanceof MappingJackson2HttpMessageConverter);
converters.clear();
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
converters.add(converter);
converters.add(fastJsonHttpMessageConverter());
}
}
有两点需要注意:
1.如果没有配置MediaType.APPLICATION_JSON_UTF8,默认值是MediaType.ALL,FastJsonHttpMessageConverter会去处理消息格式为"text/html;charset=UTF-8"
2.在RsponseBody注解下,Spring处理返回值为String时会用到StringHttpMessageConverter,我们只需要在配置文件中设置好他的编译编码就ok了
如果想了解StringHttpMessageConverter的使用,可以看这篇博客:https://blog.csdn.net/x_iya/article/details/77872173
spring,springBoot配置类型转化器Converter以及FastJsonHttpMessageConverter,StringHttpMessageConverter 使用的更多相关文章
- Spring mvc @initBinder 类型转化器的使用
一.单日期格式 因为是用注解完完成的后台访问,所以必须在大配置中配置包扫描器: 1.applicactionContext.xml <?xml version="1.0" e ...
- SpringBoot(十七):SpringBoot2.1.1数据类型转化器Converter
什么场景下需要使用类型化器Converter? springboot2.1.1在做Restful Api开发过程中往往希望接口直接接收date类型参数,但是默认不加设置是不支持的,会抛出异常:系统是希 ...
- SpringMVC09异常处理和类型转化器
public class User { private String name; private Integer age; public String getName() { return name; ...
- jQuery源码分析系列(36) : Ajax - 类型转化器
什么是类型转化器? jQuery支持不同格式的数据返回形式,比如dataType为 xml, json,jsonp,script, or html 但是浏览器的XMLHttpRequest对象对数据的 ...
- struts2类型转化器详解(带例子)
Struts2有两种类型转化器: 一种局部,一种全局. 如何实现: 第一步:定义转化器 第二部:注册转化器 下面做一个局部类型转化器的实例. 我们在上面一片日志说过有个变量date类型的.只有我们输入 ...
- 自定义Retrofit转化器Converter
我们来看一下Retrofit的使用 interface TestConn { //这里的Bitmap就是要处理的类型 @GET("https://ss0.baidu.com/73F1bjeh ...
- spring boot配置springMVC拦截器
spring boot通过配置springMVC拦截器 配置拦截器比较简单, spring boot配置拦截器, 重写preHandle方法. 1.配置拦截器: 2重写方法 这样就实现了拦截器. 其中 ...
- 【记录】spring/springboot 配置mybatis打印sql
======================springboot mybatis 打印sql========================================== 方式 一: ##### ...
- mybatis的自定义类型转化器如何使用
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-/ ...
- Spring MVC请求参数绑定 自定义类型转化 和获取原声带额servlet request response信息
首先还在我们的框架的基础上建立文件 在domian下建立Account实体类 import org.springframework.stereotype.Controller; import org. ...
随机推荐
- 从零玩转Nginx-从零玩转nginx
title: 从零玩转Nginx date: 2023-05-13 23:08:49.074 updated: 2023-05-13 23:17:26.474 url: https://www.yby ...
- kubernetes web管理页面安装(二)
参考文件: https://cloud.tencent.com/developer/article/1919416 参考命令: https://blog.51cto.com/smbands/49038 ...
- 【scikit-learn基础】--『监督学习』之 随机森林分类
随机森林分类算法是一种基于集成学习(ensemble learning)的机器学习算法,它的基本原理是通过对多个决策树的预测结果进行平均或投票,以产生最终的分类结果. 随机森林算法可用于回归和分类问题 ...
- 斯坦福 UE4 C++ ActionRoguelike游戏实例教程 11.认识GAS & 创建自己的能力系统
斯坦福课程 UE4 C++ ActionRoguelike游戏实例教程 0.绪论 概述 本篇文章对应Lecture 16 - Writing our own Gameplay Ability Syst ...
- 我的第一个JavaWeb程序!!!
- [Python急救站]学生管理系统链接数据库
相信很多人在初学Python的时候,经常最后作业就是完成一个学生管理系统,但是我们来做一个完美的学生管理系统,并且将数据储存到数据库里. 我们先看看我们的数据库怎么设置. 首先呢,我选择用的是SQL ...
- 一图看懂CodeArts Inspector 三大特性,带你玩转漏洞管理服务
本文分享自华为云开发者联盟公众号<一图看懂华为云CodeArts Inspector三大特性,带你玩转漏洞管理服务>. 华为云漏洞管理服务CodeArts Inspector是面向 ...
- RT-DETR:可以满足实时性要求的DETR模型
本文分享自华为云社区<高性能网络设计秘笈:深入剖析Linux网络IO与epoll>,作者: Lion Long . 一.epoll简介 epoll是Linux内核中一种可扩展的IO事件处理 ...
- HDC.Cloud2021|开发者们都在谈的云原生到底长什么样?
摘要:云原生数据库基于存储与计算分离架构,与传统数据库相比,具备高性能.高扩展.一致性.易管理和多云支持等特性,在海量数据处理.智能存储.业务应用等方面表现出了强大的生命力. 近几年,云原生的风越刮越 ...
- Shell:Lite OS在线调试工具知多少
摘要:Shell作为Huawei Liteos在线调试工具,可以通过串口工具输入输出,支持常用的基本调试功能.同时用户可以新增定制的命令,新增命令需重新编译烧录后才能执行 本文分享自华为云社区< ...