---
title: "Spring MVC HTTP Status 406 - 解决方法"
author: "xsylang"
date: "2016-05-17T23:30:07Z"
tags: ["MVC", "Spring", "json"]
categories: ["行业应用"]
slug: "spring-mvc-http-status-406"
draft: false
lastmod: "2016-05-17T23:28:45Z"
id: 2298887
url: "https://xsylang.iteye.com/blog/2298887"
---

用的Spring版本是4.2.4，在用@ResponseBody标注返回json格式时候遇到这样的错误：“The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.”。字面意思很明显，产生的格式跟能接受的格式不符，对不上眼。但是各种google、stackoverflow之后，大多数答案都只是说要加上json的相关依赖之类的，试了都无用。于是跟踪代码，发现Spring默认ContentNegotiationManager使用org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy解析可接受的media type,这貌似是Spring 3哪个版本以后开始的特性，因为我的的url-pattern 是\*.htm格式的，于是解析出来能accept的media type只有text/html，自然报错。而另一个HeaderContentNegotiationStrategy根本没发挥作用。

  **一个可行的解决方案：**

  在spring-servelt中添加

&lt;bean   class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/&gt;

    &lt;bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"&gt;

        &lt;property name="messageConverters"&gt;

            &lt;list&gt;

                &lt;bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/&gt;

            &lt;/list&gt;

        &lt;/property&gt;

    &lt;/bean&gt;

这两个bean处理请求映射的，在bean中默认会创建一个使用HeaderContentNegotiationStrategy的ContentNegotiationManager，这样就能解析htttp请求头Accept中的类型了。但要**注意**的是，上述两个bean要定义在&lt;mvc:annotation-driven/&gt;之前。为什么呢？因为&lt;mvc:annotation-driven/&gt;会注册RequestMappingHandlerMapping, RequestMappingHandlerAdapter以及 ExceptionHandlerExceptionResolver等等的东西，如果上述两个bean定义放在&lt;mvc:annotation-driven/&gt;之后就不起作用了。