要解决"白标错误页面,此应用程序没有对 /error 进行显式映射,因此您看到的是一个回退页面"问题,您可以按照以下步骤进行操作:
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
// 获取错误状态码
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
// 根据错误状态码进行自定义处理
if (statusCode == HttpStatus.NOT_FOUND.value()) {
return "error-404"; // 返回自定义的 404 错误页面
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "error-500"; // 返回自定义的 500 错误页面
}
// 可以根据需要添加其他错误状态码的处理
}
return "error"; // 返回通用的错误页面
}
@Override
public String getErrorPath() {
return "/error";
}
}
在 "error.html" 页面中,您可以显示通用的错误消息。在 "error-404.html" 页面中,您可以显示 404 错误消息。在 "error-500.html" 页面中,您可以显示 500 错误消息。
@Configuration
public class ErrorConfig extends WebMvcConfigurerAdapter {
@Autowired
private CustomErrorController customErrorController;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/error").setViewName("forward:/error");
}
@Bean
public ErrorController errorController() {
return customErrorController;
}
}
通过上述步骤,您可以为应用程序的错误页面实现自定义处理,根据错误状态码显示不同的错误页面。