Jackson2HttpMessageConverter

用处

  • SpringMVC中,controller中的方法返回java Bean对象,mvc将此对象转换成字符串
  • 默认支持的mediaType: MediaType.APPLICATION_JSON, new MediaType("application", "*+json"),也就json请求

为什么改造

想让url以.html结尾的请求走json请求的逻辑

现状

当后端使用如下方法编码时,url以.html为后缀,最终会响应406状态页面
后端@RestController返回java对象

@RequestMapping(value = "/data", method = {RequestMethod.POST, RequestMethod.GET})
public ApiResult data(HttpServletRequest httpServletRequest, String type, String param, Model model) {
    return new ApiResult(2);
}

目标

修改后/data.html返回

{ "code" : 2 }

修改方式

/**
* 自定义的jackson到httpmessage的转换器
* Created by cdliujian1 on 2018/1/27.
 */
public class JMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

/**
 * Construct a new {@link MappingJackson2HttpMessageConverter} using default configuration
 * provided by {@link Jackson2ObjectMapperBuilder}.
 */
public JMappingJackson2HttpMessageConverter() {
    this(Jackson2ObjectMapperBuilder.json().build());
}

/**
 * Construct a new {@link MappingJackson2HttpMessageConverter} with a custom {@link ObjectMapper}.
 * You can use {@link Jackson2ObjectMapperBuilder} to build it easily.
 * @see Jackson2ObjectMapperBuilder#json()
 */
public JMappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
    super(objectMapper);
    List<MediaType> mediaTypes = getSupportedMediaTypes();
    List<MediaType> newMediaTypes = new ArrayList<>();
    newMediaTypes.add(MediaType.TEXT_HTML);
    newMediaTypes.addAll(mediaTypes);
    setSupportedMediaTypes(newMediaTypes);
}

}

构造函数中,调用setSupportedMediaTypes方法,将MediaType.TEXT_HTML添加到当前HttpMessageConverter支持媒体类型中
这样当.html后缀结尾的链接到后端时,可以进入到MappingJackson2HttpMessageConverter的处理流程

MvcConfiguration

@Configuration
//@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
            .indentOutput(true)
            .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    converters.add(new JMappingJackson2HttpMessageConverter(builder.build()));
    converters.add(new MappingJackson2XmlHttpMessageConverter(builder.xml().build()));
}
}
posted on 2018-01-27 16:17  j.liu&nbsp;windliu  阅读(999)  评论(0编辑  收藏  举报