动态更改注释驱动的Spring MVC中的@ResponseStatus

时间:2013-07-08 12:37:17

标签: spring-mvc spring-annotations

我真的不确定使用Spring 3.2 MVC是否可行。

我的控制器有一个声明如下的方法:

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

问题:

  1. @ResponseStatus(HttpStatus.OK)是什么意思?
  2. 是否表示该方法将始终返回HttpStatus.OK状态代码。
  3. 如果从服务层抛出异常怎么办?
  4. 我可以在发生任何异常时更改响应状态吗?
  5. 如何根据相同方法中的条件处理多个响应状态?

3 个答案:

答案 0 :(得分:27)

@ResponseStatus(HttpStatus.OK)表示如果处理方法正常返回,请求将返回OK(对于这种情况,此注释是多余的,因为默认响应状态为HttpStatus.OK)。如果处理程序抛出异常,则注释不适用。

  

如何根据同一方法中的条件处理多个响应状态?

那个问题has already been asked

  

我可以在发生任何异常时更改响应状态

你有两个选择。如果异常类是您自己的异常类,则可以使用@ResponseStatus注释异常类。另一种选择是为控制器类提供一个异常处理程序,用@ExceptionHandler注释,并让异常处理程序设置响应状态。

答案 1 :(得分:12)

如果直接返回ResponseEntity,可以在其中设置HttpStatus:

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

如果您想要返回404以外的错误,HttpStatus has lots of other values可供选择。

答案 2 :(得分:9)

您无法为@ResponseStatus设置多个状态值。我能想到的一种方法是使用@ExceptionHandler作为响应状态,而不是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(...);
}