Issue
I use Angularjs to post data to spring controller.
like this.
var user ={
"userID" : "1",
"username" : "hello",
"password" : "123456"
};
console.log(user);
var response = $http.post("/login/signup",user);
response.success(function (data) {
alert("success");
alert(data);
});
response.error(function (data) {
alert("error");
alert(data);
});
My model
public class User {
private long userID;
private String username;
private String password;
public User(){
}
public User(long userID, String username, String password) {
this.userID = userID;
this.username = username;
this.password = password;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And My controller.
@Controller
@RequestMapping(value = "/login")
public class LoginController {
@RequestMapping(value = "/signup",method = RequestMethod.POST)
public String signUp(User user){
String username = user.getUsername();// NULL!!
System.out.println(username);
return "login";
}
}
I get null user like this.
If I add @RequestBody
to my controller.I even could not get into the controller and get an exception.
@RequestMapping(value = "/signup",method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_VALUE})
public String signUp(@RequestBody User user){
String username = user.getUsername();
System.out.println(username);
return "login";
}
exception
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Solution
You may need to set Content-Type: application/json
in your request header when you are posting your data to server.
Also use:
@RequestMapping(value = "/signup",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
Insted of:
@RequestMapping(value = "/signup",method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_VALUE})
EDIT
Sometimes (I'm not sure when), MappingJackson2HttpMessageConverter
does not get registered with spring context which is responsible for converting request params to model bean. If it is not registered, registering it manually may resolve the issue.
Answered By - justAbit