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

后端 未结 1 1452
深忆病人
深忆病人 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<T> is to set the media type in the constructor, by using the super constructor AbstractHttpMessageConverter.(MediaType supportedMediaType).

     public class EmployeeConverter extends AbstractHttpMessageConverter<Employee> {
          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<T>

    2. Register you Converter

    <mvc:annotation-driven>
        <mvc:message-converters>
           ...
           <bean class="com.example.YourConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>
    

    The major drawback of <mvc:message-converters> 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: <mvc:message-converters register-defaults="true">...

    • *used by the other implementations like MappingJackson2HttpMessageConverter´
    • **example take from AbstractXmlHttpMessageConverter<T>
    0 讨论(0)
提交回复
热议问题