Custom HTTP Message Converter Not Being Used, 415 Unsupproted Media Type

后端 未结 1 1456
深忆病人
深忆病人 2020-12-09 06:03

I am creating a test application to achieve conversion from XML String to Employee object before being passed to the controller. I don\'t want to use JAXB converter because

1条回答
  •  感动是毒
    2020-12-09 06:06

    1. Set Media Type

    Comparing your implementation with some HttpMessageConverter implementations provided by Spring (for example ´MappingJackson2HttpMessageConverter´), shows that you missed to define the supportedMediaTypes.

    The common way* of HttpMessageConverter that extends AbstractHttpMessageConverter is to set the media type in the constructor, by using the super constructor AbstractHttpMessageConverter.(MediaType supportedMediaType).

     public class EmployeeConverter extends AbstractHttpMessageConverter {
          public EmployeeConverter() {
                super(new MediaType("text", "xml", Charset.forName("UTF-8")));
          }
     }
    

    BTW 1: you can also register more then one media type**

    super(MediaType.APPLICATION_XML,
          MediaType.TEXT_XML,
          new MediaType("application", "*+xml")); 
    

    BTW 2: for xml conterter one should think extending from AbstractXmlHttpMessageConverter

    2. Register you Converter

    
        
           ...
           
        
    
    

    The major drawback of is, that this replace the default configuration, so you must also register all default HttpMessageConverter explicit.

    To keep the default message convertes you need to use: ...

    • *used by the other implementations like MappingJackson2HttpMessageConverter´
    • **example take from AbstractXmlHttpMessageConverter

    0 讨论(0)
提交回复
热议问题