2016-01-21 63 views
0

我无法得到这个东西的工作。除了我尝试发布实际对象时,该项目完全可以工作。我可以发布单个字符串就好了。发布对象spring restcontroller?

HTML:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="ISO-8859-1"> 
<title>Insert title here</title> 
<script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
</head> 
<body> 
    <h1>post test</h1> 
    <button id="postButton">post</button> 
    <script> 
     var myObject = { 
      name : "Johnny", 
      field : "something" 
     }; 
     $(function() { 
      $("#postButton").click(function() { 
       $.post("posting", JSON.stringify(myObject), function(data, status) { 
        alert(status); 
       }); 
      }); 
     }); 
    </script> 
</body> 
</html> 

控制器:

package app.controllers; 

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.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 

import model.MyObject; 

@Controller 
public class MainController { 

    @RequestMapping(value = "/posting", method = RequestMethod.POST) 
    @ResponseBody 
    public void posting(@RequestBody MyObject myObject) { 
     System.out.println(myObject.getName()); 
    } 

} 

myObject的:

package model; 

public class MyObject { 

    private String name; 

    private String field; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getField() { 
     return field; 
    } 

    public void setField(String field) { 
     this.field = field; 
    } 

} 

任何帮助将不胜感激。我在没有JSON.stringify的情况下尝试了它,它也不起作用。

回答

0

你回到什么状态?我的第一个想法是,你可能得到HTTP 415 Unsupported Media Type,因为你可能没有发送Content-Type: application/json到你的控制器。

无论您收到的错误消息都可能有助于解答。