java - Spring MVC : using @ResponseStatus(reason = '' ) on a @ResponseBody exception handler in tomcat

标签 java spring spring-mvc

有谁知道为什么我不能在 spring MVC 中的异常处理程序上使用 @ResponseStatus(reason = "My message") 同时仍然返回 @ResponseBody。似乎发生的是,如果我使用 reason 属性

// this exception handle works, the result is a 404 and the http body is the json serialised
// {"message", "the message"}
@ExceptionHandler
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public Map<String, String> notFoundHandler(NotFoundException e){
    return Collections.singletonMap("message", e.getMessage());
}

// this doesn't... the response is a 404 and the status line reads 'Really really not found'
// but the body is actually the standard Tomcat 404 page
@ExceptionHandler
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Really really not found")
public Map<String, String> reallyNotFoundHandler(ReallyNotFoundException e){
    return Collections.singletonMap("message", e.getMessage());
}

code for this example在github上结束了。

最佳答案

看来这是AnnotationMethodHandlerExceptionResolver

下面代码的直接结果
private ModelAndView getModelAndView(Method handlerMethod, Object returnValue, ServletWebRequest webRequest)
        throws Exception {

    ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(handlerMethod, ResponseStatus.class);
    if (responseStatusAnn != null) {
        HttpStatus responseStatus = responseStatusAnn.value();
        String reason = responseStatusAnn.reason();
        if (!StringUtils.hasText(reason)) {
            // this doesn't commit the response
            webRequest.getResponse().setStatus(responseStatus.value());
        }
        else {
            // this commits the response such that any more calls to write to the 
            // response are ignored
            webRequest.getResponse().sendError(responseStatus.value(), reason);
        }
    }
    /// snip
}

这已在 SPR-8251 中报告给 Springsource :

关于java - Spring MVC : using @ResponseStatus(reason = '' ) on a @ResponseBody exception handler in tomcat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637950/

相关文章:

java - 填充和导入 Excel 电子表格的 UI 替代方案

java - 在 realm.io/Android 中使用保留名称

java - 使用 Tomcat 部署 Spring 应用程序,上下文不匹配

java - 嵌套表单数据与 Spring MVC 中的对象列表绑定(bind)

java - 使用 SpringMVC,未注入(inject) DaoImpl

Spring Rest 服务 - 我尝试登录时 CSRF token 无效

java - 使RelativeLayout可滚动

java - 为什么下面的Java Stream filter方法没有抛出NullPointerException

java - 从 bufferedreader 获取空值

java - Git 克隆失败