JAVA WEB項目異常處理提示頁

最近一直感到困惑,爲啥我的後臺報錯就赤果果的將程序中的錯誤打印在頁面,這樣在項目上線後,如果遇到500,java.lang.Exception等錯誤時,會提示很尷尬的信息

感謝http://blog.csdn.net/zhangxin09/article/details/50644694

1.web.xml中配置

<error-page>  
 <exception-type>java.lang.Exception</exception-type>  
 <location>/error/error_500.jsp</location>  
</error-page>  
<error-page>  
        <error-code>403</error-code>  
   <location>/error/error_404.jsp</location>  
</error-page>  
<error-page>  
        <error-code>404</error-code>  
   <location>/error/error_404.jsp</location>  
</error-page>  
<error-page>  
        <error-code>500</error-code>  
        <location>/error/error_500.jsp</location>
</error-page>  
<error-page>  
        <error-code>503</error-code>  
        <location>/error/error_500.jsp</location>
</error-page>  
<error-page>  
        <exception-type>java.lang.NullPointException</exception-type>  
        <location>/error/error_500.jsp</location>  
</error-page>



2.在util頁面中COPY

http://blog.csdn.net/zhangxin09/article/details/50644694  中的寫法如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%!
class ErrorHandler {


// 全部內容先寫到內存,然後分別從兩個輸出流再輸出到頁面和文件  
    private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
    private PrintStream printStream = new PrintStream(byteArrayOutputStream);  
  
    /** 
     * 收集錯誤信息 
     * @param request 
     * @param exception 
     * @param out 
     */  
    public ErrorHandler(HttpServletRequest request, Throwable exception, JspWriter out) {  
        setRequest(request);  
        setException(exception);  
        if(out != null) {  
            try {  
                out.print(byteArrayOutputStream); // 輸出到網頁  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
          
         log(request);  
          
        if(byteArrayOutputStream != null)  
            try {  
                byteArrayOutputStream.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        if(printStream != null) printStream.close();  
    }  
  
    /** 
     *  
     * @param request 
     */  
    private void setRequest(HttpServletRequest request) {  
HttpSession session = request.getSession(); 
String username=(String)session.getAttribute("edu.yale.its.tp.cas.client.filter.user");
        printStream.println();  
        printStream.println("用戶賬號:" + username);  
       // printStream.println("用戶賬號:" + request.getSession().getAttribute("userName"));  
        printStream.println("訪問的路徑: "   + getInfo(request, "javax.servlet.forward.request_uri", String.class));  
        printStream.println("出錯頁面地址: " + getInfo(request, "javax.servlet.error.request_uri", String.class));  
        printStream.println("錯誤代碼: "     + getInfo(request, "javax.servlet.error.status_code", int.class));  
        printStream.println("異常的類型: "   + getInfo(request, "javax.servlet.error.exception_type", Class.class));  
        printStream.println("異常的信息: "   + getInfo(request, "javax.servlet.error.message", String.class));  
        printStream.println("異常servlet: "  + getInfo(request, "javax.servlet.error.servlet_name", String.class));  
        printStream.println();  
          
        // 另外兩個對象  
        getInfo(request, "javax.servlet.jspException", Throwable.class);  
        getInfo(request, "javax.servlet.forward.jspException", Throwable.class);  
  
        Map<String, String[]> map = request.getParameterMap();  
  
        for (String key : map.keySet()) {  
            printStream.println("請求中的 Parameter 包括:");  
            printStream.println(key + "=" + request.getParameter(key));  
            printStream.println();  
        }  
          
        for (Cookie cookie : request.getCookies()){  // cookie.getValue()  
            printStream.println("請求中的 Cookie 包括:");  
            printStream.println(cookie.getName() + "=" + cookie.getValue());  
            printStream.println();  
        }  
  
    }  
  
    /** 
     *  
     * @param exception 
     */  
    private void setException(Throwable exception) {  
        if (exception != null) {  
            printStream.println("異常信息");  
            printStream.println(exception.getClass() + " : " + exception.getMessage());  
            printStream.println();  
  
            printStream.println("堆棧信息");  
            exception.printStackTrace(printStream);  
            printStream.println();  
        }  
    }  
  
        /** 
         *  
         * @param request 
         */  
        private void log(HttpServletRequest request) {  
            File dir = new File(request.getSession().getServletContext().getRealPath("/errorLog"));  
            if (!dir.exists()) {  
                dir.mkdir();  
            }  
              
            String timeStamp = new java.text.SimpleDateFormat("yyyyMMddhhmmssS").format(new Date());  
            File file = new File(dir.getAbsolutePath() + File.separatorChar + "error-" + timeStamp + ".txt");  

        }  
  
        /** 
         *  
         * @param request 
         * @param key 
         * @param type 
         * @return 
         */  
        @SuppressWarnings("unchecked")  
        private <T> T getInfo(HttpServletRequest request, String key, Class<T> type){  
            Object obj = request.getAttribute(key);  
            return obj == null ? null : (T) obj;  
        }  


}
%>




3.在error_500.jsp中引入

<%@ page language="java" pageEncoding="UTF-8" isErrorPage="true"%>
<%@ page import="java.io.PrintStream" %>
<%@ include file="../error/util.jsp"%> 
<%
String path = request.getContextPath(); 
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path;
if (!path.endsWith("/")) {
basePath = basePath + "/";
}
%>
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>新版BMS支撐系統</title>
    <link rel="stylesheet" type="text/css" href="<%=basePath%>css/common.css"/>
    <link rel="stylesheet" type="text/css" href="<%=basePath%>css/main.css"/>
    <style>
     textarea {  
         width: 100%;  
         min-height: 300px;  
     } 
     </style> 
    <script type="text/javascript" src="<%=basePath%>js/libs/modernizr.min.js"></script>
</head>
<body>
    
        <div class="crumb-wrap">
            <div class="crumb-list"><i class="icon-font"></i><a href="#">首頁</a><span class="crumb-step">></span><span class="crumb-name">系統錯誤提示505</span></div>
        </div>
        <div class="result-wrap">
                <div class="config-items">
                    <div class="result-content">
                        <table width="100%" align="center" class="insert-tab">
                            <tbody>
                          <tr>
                              <td><img src="images/icon_cry.png"/><br/>
                              <h3>500或者503或者java.lang.NullPointException或者java.lang.Exception</h3>
                              <span style="font-size:14px;color:red;">親愛的同事:<br/>
                              您好!<br/>
                              我們致力打造更好的運營後臺,但人算不如天算,有些錯誤發生了,希望是在控制範圍內的...<br/>
如果錯誤重複出現,請向咱們的碼農同事反饋。<br/>
錯誤信息如下:<br/></span>
</td>
                          </tr>
                          <tr>
                             <td>
                             <textarea>
                            <%  
           new ErrorHandler(request, exception, out);  
        %>
        </textarea>
 </td>
                          </tr>
                                <tr>
                                    <td>
                                        <input type="button" value="返回" onclick="history.go(-1)" class="btn btn6">
                                    </td>
                                </tr>
                            </tbody></table>
                    </div>
                </div>
        </div>
        
</body>
</html>


到此完結,看效果


一定注意<%@ page language="java" pageEncoding="UTF-8" isErrorPage="true"%>將isErrorPage="true"設置爲TRUE



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章