Spring自定义错误页面配置无效求助(非web.xml方式)
Hey there! I’ve run into this exact issue before, so let’s walk through why your setup isn’t working and how to fix it.
First, Let’s Identify the Problem
Your current configuration has two key issues blocking your custom error page:
- Excluding
ErrorMvcAutoConfigurationis overkill: This auto-configuration class handles core routing for error requests—removing it breaks the default pipeline that would route requests to yourErrorController. - The
ErrorControllerimplementation is outdated: ThegetErrorPath()method was deprecated in Spring Boot 2.3+, so relying on it won’t work as expected in newer versions.
Step-by-Step Fixes
1. Update Your application.properties
Remove the auto-configuration exclusion line—you only need to disable the whitelabel error page:
server.error.whitelabel.enabled=false
2. Use a Simplified, Up-to-Date Error Controller
Replace your existing ErrorController with this version, which handles error status codes properly and avoids deprecated methods:
import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class CustomErrorController { @RequestMapping("/error") public String handleError(HttpServletRequest request) { // Get the error status code from the request Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if (status != null) { Integer statusCode = Integer.valueOf(status.toString()); // Return specific error pages based on status code if (statusCode == HttpStatus.NOT_FOUND.value()) { return "error404"; // Make sure this matches your template name } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) { return "error500"; } } // Fallback to a generic error page if no status code matches return "error"; } }
3. Verify Your Template Location
Make sure your error templates are in the correct place for your view resolver:
- For Thymeleaf: Place
error404.html,error500.html, etc., insrc/main/resources/templates/ - For JSP: Place them in
src/main/webapp/WEB-INF/views/(or your configured JSP directory)
Alternative: No Controller Required!
If you want an even simpler setup, skip writing a controller entirely. Spring Boot automatically maps error status codes to templates in an error directory. Just create this structure:
src/main/resources/templates/ └── error/ ├── 404.html ├── 500.html └── error.html (generic fallback)
With this setup, Spring Boot will automatically serve 404.html for invalid links, as long as server.error.whitelabel.enabled=false is set in your properties.
Final Checks
- Restart your application after making these changes—Spring Boot sometimes caches configuration changes.
- Test invalid links (like
/bad-url) to confirm your customerror404page loads instead of the whitelabel error or a blank page.
内容的提问来源于stack exchange,提问作者Tanya

