Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)
The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
Suppose we have a custom Response object:
public class ResponseTransfer {
private String text;
// standard getters/setters
}
Next, the associated controller can be implemented:
@Controller
@RequestMapping("/post")
public class ExamplePostController {
@Autowired
ExampleService exampleService;
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(
@RequestBody LoginForm loginForm) {
return new ResponseTransfer("Thanks For Posting!!!");
}
}
In the developer console of our browser or using a tool like Postman, we can see the following response:
{"text":"Thanks For Posting!!!"}
Remember, we don't need to annotate the @RestController-annotated controllers with the @ResponseBody annotation since Spring does it by default
let's implement a new method, mapped to the same /content path, but returning XML content instead:
@PostMapping(value = "/content", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ResponseTransfer postResponseXmlContent(
@RequestBody LoginForm loginForm) {
return new ResponseTransfer("XML Content!");
}