如何在独特的错误页面中使用 Thymeleaf 开关管理 HTTPStatus html

How manage HTTPStatus with Thymeleaf switch in unique error page html

我创建了一个自定义控制器来管理不同的错误:

@ControllerAdvice
public class MyErrorController {


    private static Logger logger = LoggerFactory.getLogger(ErrorController.class);

    @ExceptionHandler(UpdatableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String indirizzoErrato(UpdatableException ex, final Model model) {
        logger.error("Indirizzo errato", ex);
        String errorMessage = (throwable != null ? ex.getMessage() : "Unknown error");
        model.addAttribute("errorMessage", errorMessage);
        return "error";
    }

    @ExceptionHandler(ReservedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String erroreServer(ReservedException ex, final Model model) {
        logger.error("Errore Server", ex);
        String errorMessage = (ex != null ? ex.getMessage() : "Unknown error");
        model.addAttribute("errorMessage", errorMessage);
        return "error";
    }

}

但我希望根据来自名为 error:

的唯一页面 html 中 HTTPStatus 响应的错误,查看不同的消息(和图像)
      <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Indirizzo Errato</title>
<head>
        <title>Errore</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="css/main.css" th:href="@{/css/main.css}" />
    </head>
    <body>
        <img class= "404" src="/images/NotFound.jpg">    
    </body>
</html>

当我 运行 我的代码时,我没有,在控制台上我有这条消息:"ERROR 10212 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat-7].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]"

你能帮帮我吗?

谢谢!

您可以使用自定义错误控制器通过您的 html 页面显示自定义错误消息..

这里我给出我的代码来帮助你,你可以 return 基于 statusCode 值的不同错误页面....或者发送相同的错误页面并将消息设置到 html 页面

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
        model.addAttribute("statusCode",statusCode);
        if(statusCode==404){
            model.addAttribute("imgSrc","/img/fotFound.png");
        }else if(statusCode == 500){
            model.addAttribute("imgSrc","/img/internallError.png");
         }
        model.addAttribute("errorMessage","Error code : "+statusCode);
        return "error";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

并更改您的 html 代码,如下所示

<body>
    <img class= "404" th:src="${imgSrc}"> // set here your src which send form controller
</body>