springboot thymeleaf 404 自定义处理

springboot使用 thymeleaf maven 加入        

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

如果没引入的话,URL正确也会404异常。

处理404异常

方法一:

最简单的是在 project\src\main\resources\templates 目录下新建 error.html。

方法二:

如果我们想在HttpServletRequest中加入数据(request.setAttribute("key", value);或者model.addAttribute("key", value);),在404页面显示数据的话可以写个conroller implements org.springframework.boot.autoconfigure.web.ErrorController:

@Controller
public class RedirectUnknownUrls implements ErrorController{
    @GetMapping("/error")
    public String redirectNonExistentUrlsToErrorHtml(Model model)  {
        model.addAttribute("hello","hello CSDN");
        return "error";
    }
    @Override
    public String getErrorPath() {
        return "/error";
    }
}
<p th:text="${hello}"></p>      ->    <p>hello CSDN</p>

猜你喜欢

转载自blog.csdn.net/u011164906/article/details/78984268