1. 程式人生 > >HTTP 415 錯誤 – 不支援的媒體型別(Unsupported media type)

HTTP 415 錯誤 – 不支援的媒體型別(Unsupported media type)

   前段時間在使用@RequestBody註解的時候遇到了一個以前沒遇到過的錯誤,HTTP 415  Unsupported media type? 這個是個什麼鬼,@ResponseBody可以正常工作而一使用@RequestBody來進行互動就會報這個錯誤。一直請求不到Controller,我開始總以為是路徑或者json格式不對的問題,上網查資料大多也說的是這個問題。可是我已經寫了

data : JSON.stringify(user),  

dataType : 'json',

contentType : 'application/json;charset=UTF-8',

按照網上的辦法也一直不管用,百思不得其解。於是繼續在網上找資料,

網上分析原因很多,但找了很久都沒解決,基本是以下幾類:

  • springmvc新增配置、註解;
  • pom.xml新增jackson包引用;
  • Ajax請求時沒有設定Content-Type為application/json
  •  傳送的請求內容不要轉成JSON物件,直接傳送JSON字串即可
各種辦法都嘗試了一遍,還是沒有能解決問題;
<script>
	jQuery(function($){
	var urlStr = "<%=request.getContextPath()%>/user/GetUser";
		var user = {
			"id" : 6,
			"userName" : "小紅",
			"password" : "123",
			"age" : 12
		};
		$.ajax({
			url : urlStr,
			type : "POST",
			data : JSON.stringify(user), //轉JSON字串  
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', //contentType很重要     
			success : function(result) {
				console.log(result);
				//alert(result);
				//data = eval("(" + result + ")");
				//alert(data);
				$("#a").html(result.userName);
			}
		});
	});
</script>
造了一個簡單是資料來測試,還是不行。。
package com.cn.hnust.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.hnust.domain.User;
import com.cn.hnust.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private IUserService userService;

	@RequestMapping("/showUser")
	public String toIndex(HttpServletRequest request, Model model) {
		// int userId = Integer.parseInt(request.getParameter("id"));
		// User user = this.userService.getUserById(userId);
		// model.addAttribute("user", user);
		return "showUser";
	}

	@RequestMapping(value = "/GetUser", method = RequestMethod.POST)
	public @ResponseBody
	User GetUser(@RequestBody User user) {
		user.setUserName("Wei");
		return user;
	}

}

控制器也很簡單,可是就是請求不到Controller方法。於是我繼續在網上尋找資料,直到看到一篇部落格,才找到了問題的解決辦法。

原來是Jackson的依賴問題,spring3.x和spring4.x是不同的:

spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

具體可以檢視spring-web的jar確認,哪個存在用哪個!

在配置ViewResolver的時候應該指定響應的版本,於是我將springmvc的配置檔案改為:

<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
				<entry key="xml" value="application/xml" />
				<entry key="htm" value="text/html" />
			</map>
		</property>

		<property name="defaultViews">
			<list>
				<!-- JSON View -->
				<bean
					class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
				</bean>
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>


僅僅將
MappingJacksonJsonView
改為
MappingJackson2JsonView

就解決了之前的415的問題。。。