1. 书写 configration的bean
@Configuration public class ErrorConfig implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { // TODO Auto-generated method stub ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/error400Page"); ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error401Page"); ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error404Page"); ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error500Page"); registry.addErrorPages(error400Page,error401Page,error404Page,error500Page); } }
2 书写 controller
@Controller public class ErrorController { @RequestMapping(value = "/error400Page") public String error400Page(Model model) { model.addAttribute("code","400错误"); model.addAttribute("msg","......"); return "404"; } @RequestMapping(value = "/error401Page") public String error401Page(Model model) { model.addAttribute("code","401错误"); model.addAttribute("msg","......"); return "404"; } @RequestMapping(value = "/error404Page") public String error404Page(Model model) { model.addAttribute("code","404错误"); model.addAttribute("msg","找不到页面......"); return "404"; } @RequestMapping(value = "/error500Page") public String error500Page(Model model) { model.addAttribute("code","500错误"); model.addAttribute("msg","服务器参数错误......"); return "404"; } }
3 书写jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>error page</title> <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 可选的 Bootstrap 主题文件(一般不用引入) --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <jsp:include page="/indexHeader.jsp"></jsp:include> <h1 align="center" style="margin-top:150px">${code}</h1> <h2 align="center" style="margin-bottom:150px">${msg}</h2> <jsp:include page="/indexFooter.jsp"></jsp:include> </body> </html>