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

SpringMVC HttpMessageConverter 詳解與 415 錯誤排查指南

     編輯:Java 相關知識

現象:HTTP 415 Unsupported Media Type

前端 Ajax POST 請求,後端 @RequestBody 接收參數,控制台拋 415。根因:**請求頭 Content-Type 與 SpringMVC 內置的消息轉換器不匹配**。

HttpMessageConverter 核心機制

責任鏈模式:SpringMVC 按順序遍歷已註冊的 HttpMessageConverter,調用 canRead(clazz, mediaType) 判斷是否支持當前請求 Content-Type,支持則調用 read() 反序列化為 Java 對象。

內置轉換器對照表

轉換器支持 MediaType用途
ByteArrayHttpMessageConverterapplication/octet-stream二進制流直讀寫
StringHttpMessageConvertertext/plain, */*字符串直接讀寫
ResourceHttpMessageConverterapplication/octet-streamResource 對象
FormHttpMessageConverterapplication/x-www-form-urlencoded
multipart/form-data
表單數據
MappingJackson2HttpMessageConverterapplication/jsonJSON ↔ POJO (Jackson)
Jaxb2RootElementHttpMessageConverterapplication/xml, text/xmlXML ↔ POJO (JAXB)

415 錯誤常見原因與解決

1. 缺少 Jackson 依賴

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

SpringMVC 3.1+ 自動檢測 classpath 中 Jackson,無需手動註冊。

2. 請求頭 Content-Type 錯誤

// jQuery Ajax
$.ajax({
  url: '/api/user',
  type: 'POST',
  contentType: 'application/json;charset=UTF-8', // 必須顯式聲明
  data: JSON.stringify({name: 'Tom', age: 18}),
  success: ...
});

3. 手動註冊 StringHttpMessageConverter (兼容 text/plain)

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List> converters) {
        // 預設轉換器已含 Jackson,這裡補充 String 支持
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        // 若需自定義 Jackson 配置
        // converters.add(new MappingJackson2HttpMessageConverter(customObjectMapper()));
    }
}

4. 全局配置法 (XML)

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes">
        <list><value>text/plain;charset=UTF-8</value></list>
      </property>
    </bean>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
  </mvc:message-converters>
</mvc:annotation-driven>

響應端:@ResponseBody 與 Accept 頭

  • 返回值自動經 HttpMessageConverter 寫出。
  • 客戶端 Accept: application/json → 選擇 Jackson 輸出 JSON。
  • 推薦:Controller 方法直接返回 POJO/Map/List,配合 @RestController (等同 @Controller + @ResponseBody)。

排查清單

  1. 依賴:jackson-databind 是否在 classpath?
  2. 請求頭:Content-Type: application/json;charset=UTF-8?
  3. 參數:JSON 格式是否合法 (雙引號、無尾逗號)?
  4. 實體類:是否有無參構造器、字段名與 JSON key 對應?
  5. 轉換器:WebMvcConfigurer 是否誤覆蓋默認列表?

總結

415 本質是「媒體類型不匹配」。確保 依賴完整、請求頭正確、轉換器齊全 三要素,即可消除 99% 的 415 錯誤。掌握 HttpMessageConverter 責任鏈機制,還能靈活擴展自定義協議(如 Protobuf、MessagePack)。

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