在SpringMVC中使用@RequestBody和@ResponseBody注解处理json时,报出HTTP Status 415的解决方案

我在使用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;
    }
    
}
原文地址:https://www.cnblogs.com/lz2017/p/7296260.html