Spring MVC:使用HttpMessageConverters正确配置WebMvcConfigurerAdapter

时间:2017-03-07 17:17:28

标签: spring spring-mvc spring-rest

使用Spring Framework 4.3.6

关于MVC,声明:

@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

使用:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
   converters.add(httpMessageConverterConfig.stringHttpMessageConverter());
   converters.add(httpMessageConverterConfig.mappingJackson2XmlHttpMessageConverter());
   converters.add(httpMessageConverterConfig.mappingJackson2HttpMessageConverter());
}

因此:

  1. 字符串
  2. XML
  3. 的Json
  4. 对于某些@Test方法失败

    在哪里工作:

    resultActions = mockMvc.perform(get(uri).accept(MediaType.APPLICATION_JSON_UTF8))
                        .andDo(print());
    

    感谢:.andDo(print());我可以看到以下内容:

    MockHttpServletRequest:
          HTTP Method = GET
          Request URI = /personas
           Parameters = {}
              Headers = {Accept=[application/json;charset=UTF-8]}
    
    Handler:
                 Type = ....
               Method = public com.manuel....
    
    Async:
        Async started = false
         Async result = null
    
    Resolved Exception:
                 Type = null
    
    ModelAndView:
            View name = null
                 View = null
                Model = null
    
    FlashMap:
           Attributes = null
    
    MockHttpServletResponse:
               Status = 200
        Error message = null
              Headers = {Content-Type=[application/json;charset=UTF-8]}
         Content type = application/json;charset=UTF-8
                 Body = <collection>
      <item>
        <id>087</id>
        <nombre>Leonardo</nombre>
        <apellido>Jordan</apellido>
      </item>
      ....
    </collection>
    

    观察:

    • 对于MockHttpServletRequestMockHttpServletRequest标题是正确的。两者都与JSON
    • 相关
    • 对于MockHttpServletRequest,即使标题与JSON相关,请注意正文位于XML

    因此错误信息是:

    java.lang.AssertionError: No value at JSON path "collection", exception: Property ['collection'] not found in path $
        at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:245)
    

    如果客户是RestTemplate

    通过以下方式定义或创建:

    RestTemplate restTemplate = new RestTemplate(new MockMvcClientHttpRequestFactory(mockMvc));
    

    使用:

    requestEntity = RequestEntity.get(uri).accept(MediaType.APPLICATION_JSON_UTF8)
                                                          .build();
    

    错误是:

    org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
     at [Source: java.io.ByteArrayInputStream@5874adee; line: 1, column: 2]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
     at [Source: java.io.ByteArrayInputStream@5874adee; line: 1, column: 2]
    

    好奇的是:

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
       converters.add(httpMessageConverterConfig.stringHttpMessageConverter());
       converters.add(httpMessageConverterConfig.mappingJackson2XmlHttpMessageConverter());
       converters.add(httpMessageConverterConfig.mappingJackson2HttpMessageConverter());
    }
    

    再次:

    1. 字符串
    2. XML
    3. 的Json
    4. 更改为:

      @Override
      public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
         converters.add(httpMessageConverterConfig.stringHttpMessageConverter());
         converters.add(httpMessageConverterConfig.mappingJackson2HttpMessageConverter());
         converters.add(httpMessageConverterConfig.mappingJackson2XmlHttpMessageConverter());
      
      }
      
      1. 字符串
      2. 的Json
      3. XML
      4. 现在一切正常。因此,列表的顺序至关重要。

        为什么会这样? 还是缺少其他东西?

        要求声明列表,无需项目的顺序和信任HTTP标头。

0 个答案:

没有答案