自定义web错误页与找不到页(400与500)
<error-page><exception-type>java.lang.Throwable</exception-type><location>/WEB-INF/views/error/500.jsp</location></error-page><error-page><error-code>500</error-code><location>/WEB-INF/views/error/500.jsp</location></error-page><error-page><error-code>404</error-code><location>/WEB-INF/views/error/404.jsp</location></error-page>
?在 web项目的/WEB-INF/views/error文件夹下定义404.jsp与500.jsp
404.jsp示例:
<%@ page contentType="text/html;charset=UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%response.setStatus(200);%><!DOCTYPE html><html><head><title>404 - 页面不存在</title></head><body><h2>404 - 页面不存在.</h2><p><a href="<c:url value="/"/>">返回首页</a></p></body></html>
?500.jsp示例:
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ page import="org.slf4j.Logger,org.slf4j.LoggerFactory" %><%response.setStatus(200);%><%Throwable ex = null;if (exception != null)ex = exception;if (request.getAttribute("javax.servlet.error.exception") != null)ex = (Throwable) request.getAttribute("javax.servlet.error.exception");//记录日志Logger logger = LoggerFactory.getLogger("500.jsp");logger.error(ex.getMessage(), ex);%><!DOCTYPE html><html><head><title>500 - 系统内部错误</title></head><body><h2>500 - 系统发生内部错误.</h2><p><a href="<c:url value="/"/>">返回首页</a></p></body></html>
?
然后服务器的所有报错都会跳转到500.jsp,所有页面找不到的请求都会转发到404.jsp.
其中500.jsp与404.jsp可根据自己项目灵活定制.
注意不要少了?<%response.setStatus(200);%> 这句话,以设置服务器返回的HTTP状态!