Paul
Paul

Reputation: 419

Call Spring REST WebService with jQuery

I want to call a Spring REST WebService with JQuery.

I have two methods in my controller:

@RequestMapping(value="/{id}", method=RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable long id, Model model){
return new User("TestUser");
}

@RequestMapping(value="/{id}", method=RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateUser(@PathVariable long id, @Valid User user){
    user.getName();
}

The class User looks like this:

public class User {

private String name;

public User(){};
public User(String name){this.name = name;}

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

}

Now when I call http://localhost:8080/demo/user/2 the result is {"name":"TestUser"} like expected.

But when trying to modify a resource I try like this:

$.ajax({
  url: "http://localhost:8080/demo/user/2",
  dataType: "json",
  data: '{"name":"NewTestUser"}',
  type: "PUT",
  success: function(){alert('success');}
});

I can see in Debugmode that the proper method (updateUser) is called, but the instance variable name of the User object is always null. Can anybody tell me what I am doing wrong? Thanks!

Upvotes: 1

Views: 2212

Answers (1)

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

You will also have to annotate the User parameter with @RequestBody, this will trigger the httpmessageconverters registered with Spring MVC to convert the http body to your User type, this way:

@RequestMapping(value="/{id}", method=RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateUser(@PathVariable long id, @RequestBody @Valid User user){
    user.getName();
}

Upvotes: 5

Related Questions