I'm using Spring MVC to create a RESTfull API that is used by an AngularJS client. The read is working fine but when I'm trying to PUT some data from the client to the server, the @ModelAttribute object has allways null data (the test
object it self is not null).
I have looked with firebug at the request, and tha data is there.
Do I need to configure something in order to convert the json to the mapped model?
Here is the Controller:
@Controller
@RequestMapping("/test")
public class TestController {
@SuppressWarnings("UnusedDeclaration")
protected TestController() {
}
@RequestMapping(value = "data", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public TestResource getTest(){
TestResource resource = new TestResource();
resource.setId(LinkBuilderUtil.linkTo(TestController.class).slash("1").withSelfRel());
resource.setValue1("value1");
resource.setValue2("value2");
return resource;
}
@RequestMapping(value = "/update", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
@Transactional
public void updateParty(@ModelAttribute TestResource test) {
String str="xxx";
}
}
And here is how I create the request:
$scope.save = function () {
var headers = { 'Content-Type':'application/json' };
$http.put($scope.url, $scope.updatedJson, { headers: headers });
The TestResource:
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestResource {
String value1;
String value2;
Link id;
public TestResource(){
}
public TestResource(String id, String value1, String value2){
this.id = LinkBuilderUtil.linkTo(TestController.class).slash(id).withSelfRel();
this.value1 = value1;
this.value2 = value2;
}
public Link getId() {return id;}
public String getValue1() {return value1;}
public String getValue2() {return value2;}
public void setValue1(String value1) {this.value1 = value1;}
public void setValue2(String value2) {this.value2 = value2;}
public void setId(Link id) {this.id = id;}
}
And the request data:
{
"value1": "value1",
"value2": "newValue",
"id": {
"rel": "self",
"href": "http:\/\/localhost:8080\/cim\/test\/1",
"variableNames": [],
"variables": [],
"templated": false
}
}
You need to replace @ModelAttribute
with @RequestBody
and of course have the Jackson 2.x library on the classpath.
You will also need to add @JsonIgnoreProperties(ignoreUnknown = true)
to TestResource
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestResource {
//all the rest of your code
}
because the Link you are posting contains properties that the Link
object does not contain.
As was very correctly mentioned by OP, the @JsonIgnoreProperties
annotation needs to be imported from com.fasterxml.jackson.annotation
not from org.codehaus.jackson.annotate
since the latter is from Jackson 1.x