Wednesday, June 5, 2013

Spring MVC - HTTP Status 406

If you have encountered following errors with Spring MVC returning JSON response using @ResponseBody -

  1. On the broswer when accessing a resource -> HTTP Status 406 - The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
  2. In the logs -> org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

Then here is the explanation and solution -

Say for example you have this controller -
@Controller
public class TestController {
    @RequestMapping(value = "/test")
    public @ResponseBody Test test() {
        return new Test();
    }
}
The Test POJO -
public class Test {
    private String name;

    protected String getName() {
        return name;
    }
}
Notice that the POJO has only one getter and that too protected.

You will get the mentioned errors due to the above reason.

The POJO which is getting returned as @ResponseBody must have at least one public getter.

No comments:

Post a Comment