【问题标题】:Dynamically changing the @ResponseStatus in annotation driven Spring MVC在注释驱动的 Spring MVC 中动态更改 @ResponseStatus
【发布时间】:2013-07-05 19:03:42
【问题描述】:

我真的不确定使用 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. 如何在同一方法中根据条件处理多个响应状态?

【问题讨论】:

标签: spring-mvc spring-annotations


【解决方案1】:

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

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

那个问题has already been asked

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

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

【讨论】:

  • >如果处理程序抛出异常,则注释不适用。这是什么意思?在这种情况下会有什么反应?
【解决方案2】:

您不能为@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(...);
}

【讨论】:

    【解决方案3】:

    如果你直接返回一个 ResponseEntity,你可以设置 HttpStatus :

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

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

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      相关资源
      最近更新 更多