如何修改Spring白标错误页面(White Label Error Page)的文本内容
Hey there! Great question—you don’t have to scrap the entire white label error page just to tweak its text. Let’s walk through two straightforward approaches depending on how much control you need:
1. Tweak Dynamic Error Messages (Keep the Default Page Layout)
If you only want to update the dynamic parts (like the error message for 404s), you can customize the ErrorAttributes that supply data to the white label page. Here's how:
- Create a custom component extending Spring's
DefaultErrorAttributes:
import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.Map; @Component public class CustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> errorData = super.getErrorAttributes(webRequest, options); // Target 404 errors and update the message Integer statusCode = (Integer) errorData.get("status"); if (statusCode != null && statusCode == 404) { errorData.put("message", "Error 404 - Go back!"); // Optional: Update the error type label too errorData.put("error", "Page Not Found"); } return errorData; } }
This will modify the dynamic content of the default white label page. For 404 errors, your custom message will replace the default generic text.
2. Full Control: Build a Minimal Custom Error Page
If you want to change static text too (like the "Whitelabel Error Page" title or the fallback paragraph), creating a simple error.html page is the easiest way. This replaces the default white label page but keeps things just as clean while letting you set every word:
- Create an
error.htmlfile in eithersrc/main/resources/templates(if using Thymeleaf) orsrc/main/resources/static(for plain HTML):
<html> <body> <h1>Oops! Something Went Wrong</h1> <div>Status Code: <span th:text="${status}"></span></div> <div th:if="${message}">Message: <span th:text="${message}"></span></div> <!-- Add your custom call to action --> <p><a href="/">Go back to the homepage</a></p> </body> </html>
For a dedicated 404 page, you can even create 404.html in the same folder—Spring will automatically use it for all 404 errors, no extra config needed.
Quick Note on White Label Enablement
You don’t need to set server.error.whitelabel.enabled=false for either approach. The first method uses the default white label page directly, and the second replaces it gracefully without disabling the feature.
Hope this gets you exactly the error page text you’re looking for!
内容的提问来源于stack exchange,提问作者l1den

