ajax json发布到Spring mvc Controller" 415不支持的媒体类型"

时间:2015-10-13 23:25:42

标签: jquery json ajax spring spring-mvc

嗨,所以我遇到了从我的表单中获取JSON到使用spring mvc工作的问题。我的表单是动态的,JSON作为用户在表单上填写的条件列表返回。理想情况下,我希望能够将JSON作为包含Criteria对象列表的Criterias对象来实现。 (就像我下面的模型类)我不知道这是否可行,或者是否有不同的方法可以解决它,但任何建议都会非常感激。

**目前我从ajax帖子收到415不支持的媒体类型。

CONTROLLER

@RestController   
public class Controller {
@RequestMapping(value-"/test",method=RequestMethod.GET
public ModelAndView getTest(){

ModelAndView model = new ModelAndView("test");

}
@RequestMapping(value-"/query",method=RequestMethod.POST
public ModelAndView submitTest(@RequestBody Criterias criterias){

//do stuff....
ModelAndView model = new ModelAndView("results");

}

模型

public class Criterias{
private List<Criteria> criteria = new ArrayList<Criteria>();
getter setter...
}

public class Criteria{
private String field;
private String filter;
private String operator;
private String criteria;


getters setters...
}

test.jsp的

&#13;
&#13;
$(document).ready(function() {
  $("#theButton").click(function() {
    $('#myTable').append("<tr><td><select name = 'operator'><option>AND</option><option>OR</option></select></td><td>Field:<select name='field'><option>a</option><option>b</option> <option>c</option> <option>d</option> </select> </td> <td> <select name='filter'>  <option>Contains</option> <option>Does Not Contain</option> <option>Equals</option> <option>Does Not Equal</option> </select> </td><td>  <input name='criteria' type='text'> </td><td><button type ='button' class ='rm' title = 'Remove Row'/></td></tr>")
  });
  $("#myTable").on('click', '.rm', function() {
    $(this).parent().parent().remove();
  });
});

function post() {

  $.ajax({
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: "query",
    data: JSON.stringify($('form').serializeArray())

  })

};
&#13;
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>

<form>

  <table>
    <tbod>
      <tr>
        <td>Field:
          <select name='field'>
            <option>a</option>
            <option>b</option>
            <option>c</option>
            <option>d</option>
          </select>
        </td>
        <td>
          <select name='filter'>
            <option>Contains</option>
            <option>Does Not Contain</option>
            <option>Equals</option>
            <option>Does Not Equal</option>
          </select>
        </td>
        <td>
          <input name='criteria' type='text'>
        </td>
      </tr>
    </tbod>
  </table>
  <table id='myTable'>
    <tbody>
    </tbody>
  </table>

  <input type="button" value="search" onclick="return post();">
  <input type="button" id="theButton" value="Add Criteria">

</form>
&#13;
&#13;
&#13;

更新

我试图做一些更简单的事情来缩小问题的范围,从我看到的情况来看,这似乎是杰克逊映射的一个问题。以下代码也会产生415错误。

控制器

@RestController
public class Rest{
@RequestMapping(value="/testModel",method=RequestMethod.GET)
public ModelAndView getTestModel(){
   return new ModelAndView("testModel");
}

 @RequestMapping(value="/sendTestModel",method=RequestMethod.POST)
 public String submiteTestModel(@RequestBody TestModel test){
   return test.getName();
 }
 }

MODEL

public class TestModel{

private String id;
private String name;

//getters setters....
}

testModel.jsp

&#13;
&#13;
function post() {

    $.ajax({
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          type: "POST",
          contentType: 'application/json;,
    dataType: '
          json ',
    url: "sendTestModel",
    data: JSON.stringify({id:"1",name:"Bob"})

  })

};
&#13;
<Html>
<input type="button" value="search" onclick="return post();"/>
</Html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

调用JSON.stringify($('form').serializeArray())将为您提供以下字符串

[{"name":"field","value":"a"},{"name":"filter","value":"Contains"},{"name":"criteria","value":""}]

以下是serializeArray()

documentation

显然,对于期望使用Criterias对象的JSON表示的@RestController,这是不可接受的。您的JSON字符串应该类似于

{"criteria":[{"field":"a","filter":"Contains"},{"field":"Some other field value","filter":"Some other filter value"}]}

我已经为您做了一个简单的功能:

function convertCriterias(json){
    var o = new Object();
    var criterias = [];
    var c = new Object();

    for(var i = 0; i < json.length; i++){
        c[json[i].name] = json[i].value;
    }

    criterias[0] = c;

    o.criteria = criterias;

    return JSON.stringify(o);
}

只需将JSON.stringify($('form').serializeArray())替换为convertCriterias($('form').serializeArray())

即可

修改

我相信您打算使用input type="button"代替input type="submit"向您的@RestController发送AJAX帖子。您打算在按钮的onclick事件中调用return work()而不是return post

答案 1 :(得分:0)

尝试以下选项:

  • 在您的控制器中添加RequestMapping您想要制作的内容类型。有关详细信息,请查看Producible Media Types documentation

    @ResponseBody @RequestMapping(value =&#34; / query&#34;,method = RequestMethod.POST,produce =&#34; application / json&#34;)

  • 明确指定接受请求标头,而不只是jQuery Ajax调用中的 Content-Type 标头:

    $。AJAX({
              标题:{
                     接受:&#34; application / json;字符集= UTF-8&#34 ;,
                    &#34; Content-Type&#34;:&#34; application / json;字符集= UTF-8&#34;
      },..})