package com.admin.controller; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @Controller public class CustomErrorController implements ErrorController { @RequestMapping("/error") public void handleError(HttpServletRequest request, HttpServletResponse response) throws IOException { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); response.setContentType("text/html; charset=UTF-8"); if (status != null) { int statusCode = Integer.valueOf(status.toString()); if (statusCode == HttpStatus.NOT_FOUND.value()) { response.setStatus(HttpStatus.NOT_FOUND.value()); String html = generateErrorHtml( "404", "你推开了后端的大门,却发现里面只有寂寞。", request.getRequestURI() ); response.getWriter().write(html); } } } private String generateErrorHtml(String statusCode, String title, String path) { return "" + "" + "" + " " + " " + " 错误 " + statusCode + "" + " " + "" + "" + "
" + statusCode + "
" + "
" + title + "
" + "" + ""; } }