如何重写BasicErrorController并为错误页面模型添加数据?
解决方法
你的代码有两个关键问题导致无法运行,修正后就能保留BasicErrorController原有逻辑并成功添加模型数据:
1. 语法错误
原代码里List.of("item1", item2)的item2没有加双引号,这是编译错误,应该改为"item2"。
2. 缺少必要的控制器注解与父类构造调用
BasicErrorController的构造函数需要ErrorAttributes和ErrorProperties两个参数,你必须显式调用父类构造;同时要给自定义控制器添加@Controller注解,让Spring容器识别它。
完整修正代码:
import org.springframework.boot.web.servlet.error.BasicErrorController; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.boot.web.servlet.error.ErrorProperties; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @Controller public class CustomErrorController extends BasicErrorController { // 显式调用父类构造方法,注入必要的依赖 public CustomErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) { super(errorAttributes, errorProperties); } @Override public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { ModelAndView modelAndView = super.errorHtml(request, response); // 修正语法错误,给item2添加双引号 modelAndView.getModel().put("menuItems", List.of("item1", "item2")); return modelAndView; } }
验证
启动应用后,访问一个不存在的路径触发错误页面,在错误页面模板(比如Thymeleaf的error.html)里可以通过${menuItems}获取你添加的菜单数据,比如:
<ul> <li th:each="item : ${menuItems}" th:text="${item}"></li> </ul>
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

