Issue
I have a Model class and a controller. I am posting json type data in the body of post man. But each time i'm getting an unsupported media type 415 error. Here is My Model class :
public class Model1 {
private String name;
private String password;
public Model1() {
System.out.println("In the Model");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Model1 [name=" + name + ", password=" + password + "]";
}
}
And My Controller is :
@Controller
@ResponseBody
public class EcomController {
@RequestMapping(value="/getLogin", method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE)
public String getLoginStatus(@RequestBody Model1 name){
return "successfully called Post"+name.toString();
}
}
I have used HttpServletRequest in the place of @RequestBody and it worked. But Why its not woking when I am using @RequestBody?
This is the postman snapshot. Here is the image of request from postman
{
"name": "anshsh",
"password": "vbvfjh"
}
This is the Screen shot of headers used in the request
Solution
I found the mistake in my configuration file.
adding <mvc:annotation-driven />
solved the problem.
Explanation :
My program was running well but problem was on Mapping the String (Json) into java objects. So there was some issue in default Mapping classes. Although, jackson was present in class-path, It wasn't working.
<mvc:annotation-driven />
this tag would register the HandlerMapping and HandlerAdapter required to dispatch requests to your @Controllers. In addition, it also applies some defaults based on what is present in your classpath. Such as: Support for reading and writing JSON, if Jackson is on the classpath.
Answered By - Anshu Kumar
Answer Checked By - Pedro (JavaFixing Volunteer)