dharam
dharam

Reputation: 8096

Dynamically changing the @ResponseStatus in annotation driven Spring MVC

I am really not sure if this is feasible using Spring 3.2 MVC.

My Controller has a method declared as below:

@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody List<Foo> getAll(){
    return service.getAll();
}

Questions:

  1. What is the meaning of @ResponseStatus(HttpStatus.OK) ?
  2. Does it signifies that the method will always return a HttpStatus.OK status code.
  3. What if an exception is thrown from the service layer?
  4. Can I change the Response Status on occurrence of any exception?
  5. How can I handle multiple response statuses depending on conditions in the same method?

Upvotes: 36

Views: 57845

Answers (3)

Raedwald
Raedwald

Reputation: 48682

@ResponseStatus(HttpStatus.OK) means that the request will return OK if the handling method returns normally (this annotation is redundant for this case, as the default response status is HttpStatus.OK). If the method throws an exception, the annotation does not apply; instead, the status will be determined by Spring using an exception handler.

How can I handle multiple response statuses depending on conditions in the same method?

That question has already been asked.

Can I change the Response Status on occurrence of any exception

You have two choices. If the exception class is one of your own, you could annotate the exception class with @ResponseStatus. The other choice is to provide the controller class with an exception handler, annotated with @ExceptionHandler, and have the exception handler set the response status.

Upvotes: 30

Bnrdo
Bnrdo

Reputation: 5474

You cannot set multiple status value for @ResponseStatus. One approach I can think of is to use @ExceptionHandler for response status which is not HttpStatus.OK

@RequestMapping(value =  "login.htm", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public ModelAndView login(@ModelAttribute Login login) {
    if(loginIsValidCondition) {
        //process login
        //.....
        return new ModelAndView(...);
    }
    else{
        throw new InvalidLoginException();
    }
}

@ExceptionHandler(InvalidLoginException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView invalidLogin() {
    //handle invalid login  
    //.....
    return new ModelAndView(...);
}

Upvotes: 10

Ron Lunde
Ron Lunde

Reputation: 131

If you return a ResponseEntity directly, you can set the HttpStatus in that:

// return with no body or headers    
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);

If you want to return an error other than 404, HttpStatus has lots of other values to choose from.

Upvotes: 13

Related Questions