当前位置: 动力学知识库 > 问答 > 编程问答 >

web services - 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!

网友答案:

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();
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: