首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 4.0 MVC 解決 JSON 請求返回 406 錯誤的完整指南

     編輯:Java 相關知識

前言

在 Spring 4.0 MVC 開發中,當控制器方法返回 JSON 數據時,經常會遇到 HTTP 406 (Not Acceptable) 錯誤。這通常是因為瀏覽器發送的 Accept 標頭與服務端能產生的媒體類型不匹配,或者缺少必要的 JSON 轉換器配置。本文將詳細介紹兩種主流解決方案,幫助您快速排除此問題。

方案一:使用 Jackson 2.x 库(Spring 4 官方推薦)

1. 添加 Maven 依賴

在 pom.xml 中引入 Jackson 核心包:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.1</version>
</dependency>

2. Spring 配置文件配置

在 Spring MVC 配置文件中註冊 MappingJackson2HttpMessageConverter 並設置支持的媒體類型:

<!-- 防止 IE 執行 AJAX 時彈出 JSON 下載框 -->
<bean id="mappingJacksonHttpMessageConverter" 
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>text/html;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

<!-- 啟用註解驅動並註冊消息轉換器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="mappingJacksonHttpMessageConverter" />
        </list>
    </property>
</bean>

注意:Spring 4 建議使用 RequestMappingHandlerAdapter 替代已棄用的 AnnotationMethodHandlerAdapter。

方案二:使用阿里巴巴 Fastjson(高性能替代方案)

1. 添加依賴

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.7</version>
</dependency>

2. 配置 <mvc:annotation-driven>

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <!-- Fastjson 轉換器,解決 IE 下載問題 -->
        <bean id="fastJsonHttpMessageConverter" 
              class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

常見問題排查清單

  • 確認控制器方法添加了 @ResponseBody 或類上標註 @RestController
  • 檢查瀏覽器請求頭 Accept 是否包含 application/json
  • 若使用 <mvc:annotation-driven>,確保未重複定義 HandlerAdapter
  • Jackson 版本需與 Spring 4 兼容(建議 2.4+)

總結

兩種方案各有優勢:Jackson 是 Spring 生態標準,穩定可靠;Fastjson 則在序列化性能上更有優勢。根據項目技術棧選擇即可。配置核心在於:引入正確的庫版本 + 註冊消息轉換器 + 設置支持的媒體類型。希望本文能幫助您快速解決 406 錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved