使用spring 3 restful以编程方式更改http响应状态

1Su*_*gla 6 java spring spring-mvc

我有一个像下面这样的控制器

@Controller("myController")
@RequestMapping("api")
public class MyController {

     @RequestMapping(method = RequestMethod.GET, value = "/get/info/{id}", headers = "Accept=application/json")
    public @ResponseBody
    Student getInfo(@PathVariable String info) {
.................
}




    @ExceptionHandler(Throwable.class)
    @ResponseStatus( HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public String handleIOException(Throwable ex) {
        ErrorResponse errorResponse = errorHandler.handelErrorResponse(ex);
        return errorResponse.toString();
    }

}
Run Code Online (Sandbox Code Playgroud)

控制器有一个错误处理机制,在错误处理选项中它总是返回期望失败状态代码417.但我需要根据错误类型设置动态错误Http状态代码,如500,403等.我该怎么做呢?

Mar*_*her 4

您需要更改输出值ResponseEntity的类型。在这里回答: 如何在 Spring MVC @ResponseBody 方法返回字符串中响应 HTTP 400 错误?