Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing HttpServletResponse in Spring Boot controller method

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 ?

like image 914
Rajeev Akotkar Avatar asked Dec 12 '25 07:12

Rajeev Akotkar


1 Answers

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
}
like image 140
buræquete Avatar answered Dec 13 '25 21:12

buræquete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!