Springmvc 中404/500 错误,自定义错误页面

web.xml文件
<!-- 404 页面不存在错误 -->  
<error-page>  
<error-code>404</error-code>  
<location>/error.jsp</location>  
</error-page>  
<!-- 500 服务器内部错误 -->  
<error-page>  
<error-code>500</error-code>  
<location>/error.jsp</location>  
</error-page>  
<!-- java.lang.Exception异常错误,依据这个标记可定义多个类似错误提示 -->  
<error-page>  
<exception-type>java.lang.Exception</exception-type>  
<location>/error.jsp</location>  
</error-page>  
错误页面 404.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<html>
<header>
<title>404 page</title>
<body>
<pre>
<%
    Enumeration<String> attributeNames = request.getAttributeNames();
    while (attributeNames.hasMoreElements())
    {
        String attributeName = attributeNames.nextElement();
        Object attribute = request.getAttribute(attributeName);
   out.println("request.attribute['" + attributeName + "'] = " + attribute); 
    }
%>
</pre>
异常处理页面 exception.jsp:
<%@ page contentType="text/html; charset=UTF-8" isErrorPage="true" %>
<%@ page import="java.io.*" %>
<html>
<header>
<title>exception page</title>
<body>
<hr/>
<pre>
<%
response.getWriter().println("Exception: " + exception); 

if(exception != null)
{
   response.getWriter().println("<pre>"); 
   exception.printStackTrace(response.getWriter()); 
   response.getWriter().println("</pre>"); 
}

response.getWriter().println("<hr/>"); 
%>
注意isErrorPage熟悉必须为true,才能使用exception对象。exception即捕捉到的异常。此处可以对exception进行处理,比如记录日志、重定向等等。这里把exception trace打印出来了。
500、505 等错误页面的处理类似于404。

来源:http://liaojuncai.iteye.com/blog/2034992

猜你喜欢

转载自1960370817.iteye.com/blog/2382625