Came across spring boot code snippet which has HttpServletResponse passed has an argument in the controller method
public void someApiMethod(@RequestBody MyRequest req, HttpServletResponse response) {
//some code
response.setStatus(HttpStatus.NO_CONTENT.value());
}
The same could have been achieved using ResponseEntity and I feel there is no need of passing HttpServletResponse here.Kindly advise on which is the best approach and why, considering this code is written for rest API ?
Better solution is to use @ResponseStatus for there is no real reason to add non-API arguments, such as HttpServletResponse or ResponseEntity in controller methods. Only path variables, request params, request body & headers should be the set of controller parameters for majority of cases. Plus it is more readable, maintainable, and still is usable by Swagger etc.
@ResponseStatus(code = HttpStatus.NO_CONTENT)
public void someApiMethod(@RequestBody MyRequest req) {
//some code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With