Issue
I am testing my application and i found something weird.
My code:
@RequestMapping(value = "/test/{subscriberId}", method = RequestMethod.PATCH, consumes = "application/json", produces = "application/json")
public void test(@PathVariable final String subscriberId,@RequestBody Boolean actDeact ) {
..
}
and when i make a request via postman i take 400 bad request:
but when i pass only true in the body everything works fine:
I cant understand why is happening this.
I thought my first try was the valid one. The same is happening if i wait for a String (i dont get error code 400 but is passing me all the body inside the string)
Can anyone explain it?
Solution
Try like this:
public class MyPojo
{
private Boolean actDeact;
private String subscriberId;
// you can add it if you want more ..
public Boolean getActDeact() {
return actDeact;
}
public void setActDeact(Boolean actDeact) {
this.actDeact = actDeact;
}
public String getSubscriberId() {
return subscriberId;
}
public void setSubscriberId(String subscriberId) {
this.subscriberId = subscriberId;
}
}
@RequestBody MyPojo myPojo // use it like this.
Spring would convert the incoming JSON to a MyPojo object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation).
You can refer https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc for more.
Note:
@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.
@RequestParam can be used if you want to send : String,Boolean as a parameter without wrapper.
The same way
@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.
So where you send true which is not a body with method . it cannot work or convert to json so it will return some thing 400 status code
An expansion of the 400 Bad Request response code. If you still need to know more about this you can read the document of springs. I hope this helps you.... thank you..
Answered By - KishanCS