Spring

Using @ResponseStatus for Http Status in Spring

Introduction:

In Spring MVC, we can set the status of the HttpResponse in several ways. In this tutorial, we’ll achieve it using the @ResponseStatus annotation.

We can use @ResponseStatus to mark a method or an exception class with a status code and reason that should be returned. On invoking the marked handler method or when a specified exception is thrown, the HTTP status will be set to the one defined using @ResponseStatus annotation.

With Methods:

The methods in our Spring Controller, by default, return an HTTP Status 200 (OK) on successful execution.

What if we want to return another type of HttpStatus from one of our controller methods? To do so, we can mark it with @ResponseStatus:

Optionally, we can mark our Controller class with this annotation. For such a case, the response code configuration will be applied to all the request handler methods.

We can also choose to use this annotation to mark the methods in our @ExceptionHandler and @ControllerAdvice beans.

Please note that the Spring will use @ResponseStatus only when the marked method executes successfully without any raised exceptions.

With Exception Class:

We can mark our exception class with @ResponseStatus annotation:

When Spring catches such an exception, it throws the response status based on the provided settings. Note that Spring will use the same status configuration for all subclasses unless we mark them with @ResponseStatus too.

Here, we have also specified the reason of exception.

HttpServletResponse.sendError():

Spring will call a HttpServletResponse.sendError() method when:

  • @ResponseStatus is used over a method as well as a reason is provided, Or
  • on using @ResponseStatus over an exception class

Using sendError() method implies that it’ll generate and send an HTML error page to the client. So when usingĀ @ResponseStatus in a REST Controller method, we should avoid mentioning the reason.

Conclusion:

In this quick tutorial, we looked at how we can set the status of our HttpResponse in Spring MVC. We learned the usage of @ResponseStatus with methods as well as exception classes.

 

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *