iT邦幫忙

2023 iThome 鐵人賽

DAY 19
0
Software Development

我在 Spring Boot 3 裡面挖呀挖呀挖系列 第 19

Day18 - HttpMessageConverter

  • 分享至 

  • xImage
  •  

Day18 - HttpMessageConverter

前言

昨日我們談到了content negotiation讓我們可以透過Accept Header Strategy/URL Parameter Strategy可以取得不一樣的數據類型,那麼它背後的原理是什麼呢?如果今天我還想要再加入其他的數據類型是否可以做得到呢?這就是今天我們要討論的

專案建立

create module

https://ithelp.ithome.com.tw/upload/images/20231003/20128084PSDfjzKPCb.png
https://ithelp.ithome.com.tw/upload/images/20231003/20128084xCmY8pTLA2.png

maven

<!--加入對yaml的依賴-->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>

HttpMessageConverter

原理

簡單的來說HttpMessageConverter就是作為Spring MVC與Request/Response中間橋梁,透過它做訊息的轉換讓他們可以互相溝通
https://ithelp.ithome.com.tw/upload/images/20231003/20128084V93DeChHqF.png

  1. 標註@ResponseBody會由HttpMessageConverter處理
  2. HttpMessageConverter會先進行內容協,看哪個MessageConverter support,預設的MessageConverter如下
    https://ithelp.ithome.com.tw/upload/images/20231003/20128084eTn7NHK66m.png

自訂義HttpMessageConverter

自訂義的MyYamlHttpMessageConverter

public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    private ObjectMapper objectMapper = null; //把物件轉成yaml

    public MyYamlHttpMessageConverter(){
        super(new MediaType("text","yaml", Charset.forName("UTF-8")));
        //告訴Spring Boot符合哪種類型
        YAMLFactory factory = new YAMLFactory()
                .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
        this.objectMapper = new ObjectMapper(factory);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }
    @Override  //@RequestBody
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }
    @Override //@ResponseBody 把物件寫出去
    protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        try(OutputStream os = outputMessage.getBody()){
            this.objectMapper.writeValue(os,methodReturnValue);
        }
    }
}

配置類

@Configuration
public class MyHttpMessageConvertersConfiguration  {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override //配置一個能把對象轉為yaml的messageConverter
            public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
                converters.add(new MyYamlHttpMessageConverter());
            }
        };
    }
}

Controller

@RestController
public class HelloController {

    @GetMapping("/emp")
    public Employee emp(){
        return new Employee("james","2023100401","IT","A01");
    }
}

Result
https://ithelp.ithome.com.tw/upload/images/20231003/20128084LNoi9BOIjK.png

Reference


上一篇
Day17 - Path Matching and Content Negotiation
下一篇
Day19 - Template Engines
系列文
我在 Spring Boot 3 裡面挖呀挖呀挖31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言