SpringBoot——》HttpMessageConverter消息转换器
一、HttpMessageConverter解决了什么问题
前提: HTTP 请求和响应是基于文本 的,意味着浏览器和服务器通过交换原始文本进行通信。 java 中处理业务逻辑,都是以一个个有 业务意义的对象 为处理维度的
思考: 使用 controller中的方法返回 String 类型和域模型(或其他 Java 内建对象)。 如何将对象序列化/反序列化为原始文本? 文本到java对象的阻抗问题?
解决: 由 HttpMessageConverter 处理
Http请求和响应报文本质上都是一串字符串。 请求报文——》被封装成为一个ServletInputStream的输入流,供我们读取报文,把报文转成java对象 响应报文——》被封装成为一个ServletOutputStream的输出流,来输出响应报文。
1、HttpMessageConverter接口
public interface HttpMessageConverter<T> {
boolean canRead(Class<?> clazz, MediaType mediaType);
boolean canWrite(Class<?> clazz, MediaType mediaType);
List<MediaType> getSupportedMediaTypes();
T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException;
void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException;
}
2、HttpMessageConverter处理过程
@RequestMapping(value="/test", method=RequestMethod.POST)
public @ResponseBody String test(@RequestBody String name) {
return "my name is " + name+ "";
}
在SpringMVC进入test方法前: 根据@RequestBody注解选择适当的HttpMessageConverter实现类来将请求参数解析到name变量中,具体来说是使用了StringHttpMessageConverter类,它的canRead()方法返回true,然后它的read()方法会从请求中读出请求参数,绑定到test()方法的name变量中。
当SpringMVC执行test方法后: 由于返回值标识了@ResponseBody,SpringMVC将使用StringHttpMessageConverter的write()方法,将结果作为String值写入响应报文,当然,此时canWrite()方法返回true。
二、HttpMessageConverter在SpringBoot中的配置
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public HttpMessageConverters fastJsonConfigure() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//日期格式化
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.BrowserCompatible, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
converter.setFastJsonConfig(fastJsonConfig);
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastMediaTypes.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(fastMediaTypes);
return new HttpMessageConverters(converter);
}
}
上一篇:
IDEA上Java项目控制台中文乱码
