Spring MVC - @ResponseStatus Examples

Spring MVC 

This annotation marks a handler method or exception class with the status code() and reason() that should be returned.

The status code is applied to the HTTP response when the handler method is invoked and overrides status information set by other means, like ResponseEntity or "redirect:".

public @interface ResponseStatus {

HttpStatus value() default HttpStatus.INTERNAL_SERVER_ERROR;

HttpStatus code() default HttpStatus.INTERNAL_SERVER_ERROR;

String reason() default "";


When using @ResponseStatus on an exception class, the HttpServletResponse#sendError(int statusCode, java.lang.String reasonMsg) method will be used instead of ResponseStatus#reson()

This annotation can also be used on a controller class level and is then applied to all @RequestMapping handler methods.

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType
public void handleFormRequest (@RequestBody MultiValueMap<String, String> formParams) {
System.out.println("form params received " + formParams);

@RequestMapping(method = RequestMethod.PUT,
public void handleFormPutRequest (@RequestBody MultiValueMap<String, String> formParams) {
System.out.println("form params received " + formParams);
Original Post

    @RequestMapping(method = RequestMethod.GET,
produces = MediaType.APPLICATION_XML_VALUE)
public UserList handleAllUserRequest () {
UserList list = new UserList();
return list;
Original Post

package com.logicbig.example;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

public class UserNotLoggedInException extends Exception {

public UserNotLoggedInException (String message) {
package com.logicbig.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

public class ExampleController {

public String handleRequest (HttpServletRequest request)
throws UserNotLoggedInException {

Object user = request.getSession()
if (user == null) {
throw new UserNotLoggedInException("user: " + user);
return "test response " + user;

//nested exceptions
public void handleRequest2 () throws Exception {
throw new Exception(new UserNotLoggedInException(null));
Original Post

See Also