首页 > 其他分享 >spring boot学习(7)— 自定义中的 HttpMessageConverter

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

时间:2023-08-01 15:03:55浏览次数:29  
标签:code return 自定义 spring value HttpMessageConverter param type public

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

HttpMessageConverter 的声明:

public interface HttpMessageConverter<T> {

    /**
     * Indicates whether the given class can be read by this converter.
     * @param clazz the class to test for readability
     * @param mediaType the media type to read (can be {@code null} if not specified);
     * typically the value of a {@code Content-Type} header.
     * @return {@code true} if readable; {@code false} otherwise
     */
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

    /**
     * Indicates whether the given class can be written by this converter.
     * @param clazz the class to test for writability
     * @param mediaType the media type to write (can be {@code null} if not specified);
     * typically the value of an {@code Accept} header.
     * @return {@code true} if writable; {@code false} otherwise
     */
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

    /**
     * Return the list of {@link MediaType} objects supported by this converter.
     * @return the list of supported media types
     */
    List<MediaType> getSupportedMediaTypes();

    /**
     * Read an object of the given type from the given input message, and returns it.
     * @param clazz the type of object to return. This type must have previously been passed to the
     * {@link #canRead canRead} method of this interface, which must have returned {@code true}.
     * @param inputMessage the HTTP input message to read from
     * @return the converted object
     * @throws IOException in case of I/O errors
     * @throws HttpMessageNotReadableException in case of conversion errors
     */
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;

    /**
     * Write an given object to the given output message.
     * @param t the object to write to the output message. The type of this object must have previously been
     * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}.
     * @param contentType the content type to use when writing. May be {@code null} to indicate that the
     * default content type of the converter must be used. If not {@code null}, this media type must have
     * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have
     * returned {@code true}.
     * @param outputMessage the message to write to
     * @throws IOException in case of I/O errors
     * @throws HttpMessageNotWritableException in case of conversion errors
     */
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException;

}

里面有四个方法:

  1. canRead: 查看对应的类型和 content-type 头部类型是否支持被读取.
  2. canWrite: 查看对应的类型和 content-type 头部类型是否支持输出.
  3. getSupportedMediaTypes: 获取支持的类型
  4. read: 从 http 请求中,读取数据,并转化为指定类型。
  5. write: 将指定类型的实例写入到response中。

内置的常用HttpMessageConverter 类型:

  1. ByteArrayHttpMessageConverter – 转换 byte array 类型数据
  2. StringHttpMessageConverter – 根据编码格式,转化Strings
  3. ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
  4. SourceHttpMessageConverter – 转换 javax.xml.transform.Source 类型的数据。
  5. FormHttpMessageConverter – 转换 application/x-www-form-urlencoded 和 multipart/form-data 类型的消息.
  6. Jaxb2RootElementHttpMessageConverter – 将对象和xml转换。
  7. MappingJackson2HttpMessageConverter – 使用 jackson2 转换 json 数据和 对象实例

自定义 HttpMessageConverter 并使用

  1. 首先,自定义 HttpMessageConverter:

需要转化的对象为:

public class TestRequestInfo {
    private String key;
    private int value;
    private MultipartFile file;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public MultipartFile getFile() {
        return file;
    }

    @Override
    public String toString() {
        return "TestRequestInfo{" +
                "key='" + key + '\'' +
                ", value=" + value +
                '}';
    }
}

Converter

public class TestMessageConverter extends AbstractHttpMessageConverter<TestRequestInfo> {

    public TestMessageConverter(){
        super(new MediaType("application", "test-converter", Charset.forName("UTF-8")));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected TestRequestInfo readInternal(Class<? extends TestRequestInfo> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
        TestRequestInfo test = new TestRequestInfo();
        test.setKey(temp);
        return test;
    }

    @Override
    protected void writeInternal(TestRequestInfo testRequestInfo, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        outputMessage.getBody().write(testRequestInfo.toString().getBytes());
    }
}
  1. 注册 HttpMessageConverter:
@EnableWebMvc
@Configuration
@ComponentScan
public class MVCConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new TestMessageConverter());
    }
}
  1. 定义 Controller:
@RestController
public class TestController {
    @RequestMapping(
        value="/reports",
        method = {RequestMethod.GET, RequestMethod.POST}
    )
    public @ResponseBody
    TestRequestInfo getReports(@RequestBody TestRequestInfo requestInfo){
        System.out.println(requestInfo);
        return requestInfo;
    }
}

请求结果为:
{"key":"sdfasfasdf","value":0,"file":null}.

标签:code,return,自定义,spring,value,HttpMessageConverter,param,type,public
From: https://blog.51cto.com/u_15668812/6922252

相关文章

  • 前端Vue自定义精美商品分类组件category 可用于电商应用分类页面
    随着技术的不断发展,传统的开发方式使得系统的复杂度越来越高。在传统开发过程中,一个小小的改动或者一个小功能的增加可能会导致整体逻辑的修改,造成牵一发而动全身的情况。为了解决这个问题,我们采用了组件化的开发模式。通过组件化开发,可以有效地实现单独开发,单独维护,而且它们之间......
  • 智慧校园源码:vue2+Java+springboot+MySQL+elmentui+jpa+jwt
    智慧校园综合管理云平台源码系统主要以校园安全、智慧校园综合管理云平台为核心,以智慧班牌为学生智慧之窗,以移动管理平台、家校沟通为辅。教师—家长一学校—学生循环的无纸化管理模式及教学服务,实现多领域的信息互联互通以及校园管理一体化、信息数据化、数据自动化。智慧班牌融合......
  • SpringCloud Gateway 在微服务架构下的最佳实践
    作者:徐靖峰(岛风)前言本文整理自云原生技术实践营广州站Meetup的分享,其中的经验来自于我们团队开发的阿里云CSB2.0这款产品,其基于开源SpringCloudGateway开发,在完全兼容开源用法的前提下,做了诸多企业级的改造,涉及功能特性、稳定性、安全、性能等方面。为什么需要微服务网......
  • react使用自定义animation实现水平效果的路由切换
    例如:A组件跳B组件 A组件:importReactfrom'react';import'./A.scss'import{useNavigate}from'react-router-dom';exportdefaultfunctionA(){letnavigate=useNavigate()return(<divonClick={()=>{l......
  • SpringBoot进行参数校验的方法详解
    https://www.jb51.net/article/246275.htm在日常的接口开发中,为了防止非法参数对业务造成影响,经常需要对接口的参数进行校验。本文通过示例详细讲解了SpringBoot如何进行参数校验的,感兴趣的可以学习一下 +目录介绍在日常的接口开发中,为了防止非法参数对业务造成影响,经常......
  • Spring Boot Starter 剖析与实践
    引言对于Java开发人员来说,Spring框架几乎是必不可少的。它是一个广泛用于开发企业应用程序的开源轻量级框架。近几年,SpringBoot在传统Spring框架的基础上应运而生,不仅提供了Spring的全部功能,还使开发人员更加便捷地使用。在使用SpringBoot时,我们经常会接触到各种Spr......
  • Day20-spring
    Spring(容器框架)官网:https://spring.io/projects/spring-framework导入spring的包——-SpringWebMVC<!--https://mvnrepository.com/artifact/org.springframework/spring-webmvc--><dependency><groupId>org.springframework</groupId><ar......
  • 自定义Android菜单背景
    publicclassMenuExextendsActivity{privatestaticfinalStringTAG="android123";@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout......
  • android 自定义权限问题
    读懂Android(1):使用Android内部的DownloadProvider下载文件,并获取cache权限  --未审核  收藏Android内部提供了一个DownloadProvider,是一个非常完整的下载工具,提供了很好的外部接口可以被其他应用程序调用,来完成下载工作。同时也提供和很好的下载、通知、存储等机......
  • 自定义Android组件之带图像的TextV…
    本文为新书《Android/OPhone开发完全讲义》的内容连载。《Android/OPhone开发完全讲义》一书将在近期出版,敬请关注。 Android系统支持的图像格式)的TextView组件。在编写代码之前,先看一下Android组件的配置代码。1.<TextViewandroid:id="@+id/textview1"android:layout_width......