我在使用SpringMVC的@RequestBody和@ResponseBody注解處理JSON數據的時候,總是出現415的錯誤,說是不支持所提交數據格式,我在頁面中使用了JQuery的AJAX來發出JSON數據給服務器:
$.ajax({ type:'post', url:'${pageContext.request.contextPath }/requestJSON.action', contentType :'application/json;charset=utf-8', //數據是JSON data:'{"name":"手機","price":9999}', success:function(data){ alert(data); } });
同時也指定了contentType類型,但是還是出現了415
最后我發現是使用的jar出問題了,我原來使用的jar是:

spring版本是4.3.6,就一直出現415,最后我將jar包換成:

就可以了,是版本之間的問題
頁面代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.1.1.min.js"></script> <script type="text/javascript"> function requestJSON(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath }/requestJSON.action', contentType :'application/json;charset=utf-8', //數據是JSON data:'{"name":"手機","price":9999}', success:function(data){ alert(data); } }); } function responseJSON(){ $.ajax({ type:'post', url:'${pageContext.request.contextPath }/responseJSON.action', data:'name=手機&price=9999', success:function(data){ alert(data); } }); } </script> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>測試JSON</title> </head> <body> <input type="button" value="請求是JSON,輸出還是JSON" onclick="requestJSON()"/> <input type="button" value="請求是key/value,輸出是JSON" onclick="responseJSON()"/> </body> </html>
JSONTestController.java (控制器):
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.lynu.model.ItemsCustom; @Controller public class JSONTestController { @RequestMapping("/requestJSON.action") public @ResponseBody ItemsCustom requestJSON(@RequestBody ItemsCustom itemsCustom){ return itemsCustom; } @RequestMapping("/responseJSON.action") public @ResponseBody ItemsCustom responseJSON(ItemsCustom itemsCustom){ return itemsCustom; } }
