【Spring Boot学习总结】10.Web开发-自定义消息转换器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013517797/article/details/82284828

前面我们剖析了使用Spring MVC进行Web开发时的自动配置以及静态资源配置,本篇我们继续介绍使用Spring Boot进行Web开发时,对于消息转换器的配置。

一、消息转换器介绍

在Web工程接收请求和反馈响应的时候,请求体和响应体中的Content-Type头部和Accept头部,用于说明body中请求以及需要接收字符串是什么格式的,比如:text,json,xml等。对于请求报文,只有通过此头部,服务器才能知道怎么解析请求体中的字符串,对于响应报文,浏览器通过此头部才知道应该怎么渲染响应结果,是直接打印字符串还是根据代码渲染为一个网页。
而对于使用Java编写的Web应用,就要根据Content-Type头部,将body字符串转换为java对象,或根据Accept头部,将java对象转换客户端期望格式的字符串也是必不可少的工作。
Spring MVC为我们提供了许多默认的消息转换器(在org.springframework.http.converter下):

我们通过在特定位置添加@RequestBody和@ResponseBody来调用这些默认的消息转换器。

二、传统自定义消息转换器的方法

有时我们需要转换一些自定义格式的消息,此时需要自定义消息转换器。
在传统Web开发中,使用Spring MVC自定义消息转换器需要做两步:
(1)编写自定义转换器类
继承AbstractHttpMessageConverter<Object>类,重写其readInternal、supports以及writeInternal方法:

package cn.springboot.test;
import java.io.IOException;
import java.nio.charset.Charset;
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;

public class MyMessageConverter extends AbstractHttpMessageConverter{

	public MyMessageConverter(Charset forName, MediaType mediaType) {
		super(Charset.forName("utf-8"),new MediaType("application","x-result"));
	}

	//将接受信息转换为自己想要的数据类型  按需编写
	@Override
	protected Object readInternal(Class arg0, HttpInputMessage arg1)
			throws IOException, HttpMessageNotReadableException {
		// TODO Auto-generated method stub
		return null;
	}

	//检查是否是支持的model类型
	@Override
	protected boolean supports(Class arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	//包装转换后返回前台的信息
	@Override
	protected void writeInternal(Object arg0, HttpOutputMessage arg1)
			throws IOException, HttpMessageNotWritableException {
		// TODO Auto-generated method stub
	}

}

(2)在springmvc的配置文件中加入自定义的消息转换器

<!-- 打开springmvc的注解模式
    mvc 请求映射 处理器与适配器配置 -->
    <mvc:annotation-driven >
        <mvc:message-converters register-defaults="true">
            <bean class ="com.dzf.converter.MyMessageConverter"> <!--自己定义的消息转换器-->
            <property name = "supportedMediaTypes">
                <list>
                    <value>application/x-result;charset=utf-8</value>
                </list>
            </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

这里我们指定使用自定义消息转换器,来解析前台自定义的Content-Type为"application/x-result;charset=utf-8"的数据。

三、使用Spring Boot自定义消息转换器

使用Spring Boot进行自定义消息转换器则比传统的配置简洁一些,只需要在@Configuration配置类中添加消息转换器的@Bean,该转换器就会被Spring Boot自动加载到Spring容器中。如:

//此方法位于一个有@Configuration注解的类中
@Bean
public MyMessageConverter myMessageConverter(){
       MyMessageConverter converter  = new MyMessageConverter(Charset.forName("UTF-8"),new MediaType("application","x-result"));
        return converter;
}

上面的配置相当于自定义一个消息转换器MyMessageConverter。

还有一种方式是在继承了WebMvcConfigureAdapter父类的Spring MVC配置类中的configureMessageConverters配置自定义消息转换器:

package cn.springboot.test;
import java.nio.charset.Charset;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration //声明这是一个配置
public class MySpringMVCConfiguration extends WebMvcConfigurerAdapter {
    @Override //配置消息转换器
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MyMessageConverter myConverter  = new MyMessageConverter(Charset.forName("UTF-8"),new MediaType("application","x-result"));
        converters.add(myConverter);
    }
}


参考:
spring消息转换器源码简要分析:https://www.jianshu.com/p/2f633cb817f5
springmvc-自定义消息转换器:https://www.cnblogs.com/zfding/p/8322382.html
传智播客《Spring Boot实战与原理分析》视频课程
(https://pan.baidu.com/s/1o9M2bGI 密码:jxg8)

转载请注明出处:https://blog.csdn.net/acmman/article/details/82284828

猜你喜欢

转载自blog.csdn.net/u013517797/article/details/82284828