【问题标题】:How can I add an attribute to the error template model?如何向错误模板模型添加属性?
【发布时间】:2020-03-16 05:11:39
【问题描述】:

当 Spring 返回 404 响应时,DefaultErrorViewResolver 将返回错误视图,例如 /<static>/error/404.html。在我的例子中,这是一个 Thymeleaf 模板。

我想为所有错误模板的模型添加一个属性“X”; error/4xxerror/404error/5xx

@Controller 中,我会使用@ModelAttribute 注释为每个@RequestMapping 添加一个属性,但是这对于异常处理视图是不可能的:

模型增强方法(用于向模型添加额外数据) 用@ModelAttribute 注释。请注意,这些属性不是 可用于异常处理视图。

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc#using-controlleradvice-classes

【问题讨论】:

  • 如果可以实现的话很有趣;考虑到您引用的内容,对此表示怀疑。

标签: spring spring-boot spring-mvc thymeleaf


【解决方案1】:

这就是我最终做的事情:

@Component
public class AdditionalErrorAttributes extends DefaultErrorAttributes {

    private final SomeService service;

    public AdditionalErrorAttributes(SomeService service) {
        this.service = service;
    }

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);

        errorAttributes.put("someAttribute", service.getAttribute());

        return errorAttributes;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2018-07-30
    相关资源
    最近更新 更多