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

dha*_*ram 32 spring-mvc spring-annotations

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

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

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

问题:

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

Rae*_*ald 27

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

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

这个问题已经被问到了.

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

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


小智 12

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

// return with no body or headers    
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
Run Code Online (Sandbox Code Playgroud)

如果要返回404以外的错误,HttpStatus还有许多其他值可供选择.


Bnr*_*rdo 10

您无法为其设置多个状态值@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(...);
}
Run Code Online (Sandbox Code Playgroud)