Passing HttpServletResponse in Spring Boot controller method

Viewed 6762

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 ?

4 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
}

It depends on your particular use case.

  • If you can implement your use case without directly accessing the HttpServletResponse object, do so by any means. It is the cleaner approach.
  • You might have a scenario in which you need to access the HttpServletResponse. Such an example would be when you need to stream content back to the client, so you need direct access to the response output stream. In recent versions of Spring this can also be achieved via StreamingResponseBody, which avoids the need to directly access the response outout stream.

Spring boot (and in particular Spring MVC which is a part of spring boot in this case) provides an abstraction over low-level HttpResponse which is a part of the servlet specification.

In a nutshell, this abstraction saves you from thinking in terms of Http Protocol and allows concentrating on a business logic which is a good thing.

So if you can avoid HttpServletResponse - do it by all means (and this is what you'll usually do in your applications). You can create objects (and spring will convert them for you if its REST), you can return ResponseEntity which is "status" + "body" - spring will do all the conversions.

So consider these techniques first.

Now, sometimes you have to manipulate the response at the low level, well in this case you have to work with HttpServletResponse object.

Example of this if you want to return a binary data that cannot be easily converted. For instance, if you want to prepare a zip file and send it back as a result of HTTP request, you'll have to get a more fine-grain low-level control, in this case, it's better to start off with HttpServletResponse param passed into controller method.

I believe it is a better approach to return a ResponseEntity and use that as per your suspicious. ResponseEntity is easier to handle and a more "elegant" solution, more consistent with Spring design.

Related