Close

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 {

@AliasFor("code")
HttpStatus value() default HttpStatus.INTERNAL_SERVER_ERROR;

@AliasFor("value")
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
.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseStatus(HttpStatus.OK)
public void handleFormRequest (@RequestBody MultiValueMap<String, String> formParams) {
System.out.println("form params received " + formParams);
}

@RequestMapping(method = RequestMethod.PUT,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseStatus(HttpStatus.CREATED)
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)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public UserList handleAllUserRequest () {
UserList list = new UserList();
list.setUsers(userService.getAllUsers());
return list;
}
Original Post




package com.logicbig.example;

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

@ResponseStatus(HttpStatus.FORBIDDEN)
public class UserNotLoggedInException extends Exception {

public UserNotLoggedInException (String message) {
super(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;

@Controller
public class ExampleController {

@RequestMapping("/admin")
@ResponseBody
public String handleRequest (HttpServletRequest request)
throws UserNotLoggedInException {

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

//nested exceptions
@RequestMapping("/test")
public void handleRequest2 () throws Exception {
throw new Exception(new UserNotLoggedInException(null));
}
}
Original Post




See Also