Tomcat:Custom a common error page valve for all web application in tomcat

來源:互聯網
上載者:User

標籤:

  如果在一個Tomcat Server上會部署多個Web應用,又希望這多個Web應用共用一套錯誤頁面,而不是使用預設的錯誤頁面。就需要自訂錯誤頁面了。

  在每個web應用中都可以通過error-page來配置錯誤頁面。但是多個Web應用時,要在每個應用的web.xml中都配置一個錯誤頁面,就顯得有些麻煩了。然而希望通過在tomcat/conf/web.xml中來配置錯誤頁面,是不能實現的。因為Tomcat部署應用時會將公用的web.xml與每個web應用的web.xml進行合并,尋找頁面時,其實還是在每個web應用的目錄下尋找的。

  為了達到共用的目錄,只能自己來重寫Tomcat的預設實現了。所幸,Tomcat也是支援我們這樣去做的。

package com.fjn.frame.catalina.valves;import java.io.IOException;import java.io.InputStream;import java.io.Writer;import java.util.Scanner;import org.apache.catalina.connector.Request;import org.apache.catalina.connector.Response;import org.apache.catalina.util.RequestUtil;import org.apache.catalina.util.ServerInfo;import org.apache.catalina.valves.ErrorReportValve;/** *  * 要使用這個類來自訂錯誤頁面,需要調整 server.xml中Host的errorReportValveClass屬性值為這個類。 * 另外需要將這個類打成jar包放在tomcat/lib目錄下。 * @since tomcat 6.0 * @author [email protected] 2015年6月4日 * */public class ErrorPageValve extends ErrorReportValve {    private static final String ERROR_PAGE_NAME = "errorPage.html";    @Override    protected void report(Request request, Response response,            Throwable throwable) {        // Do nothing on non-HTTP responses        int statusCode = response.getStatus();        // Do nothing on a 1xx, 2xx and 3xx status        // Do nothing if anything has been written already        if (statusCode < 400 || response.getContentCount() > 0                || !response.isError()) {            return;        }        String message = RequestUtil.filter(response.getMessage());        if (message == null) {            if (throwable != null) {                String exceptionMessage = throwable.getMessage();                if (exceptionMessage != null && exceptionMessage.length() > 0) {                    message = RequestUtil                            .filter((new Scanner(exceptionMessage)).nextLine());                }            }            if (message == null) {                message = "";            }        }        // Do nothing if there is no report for the specified status code        String report = null;        try {            report = sm.getString("http." + statusCode);        } catch (Throwable t) {            ;        }        if (report == null)            return;        StringBuffer sb = new StringBuffer();        try {            buildHTMLFromErrorPage(sb);        } catch (Exception ex) {        }        if (sb.length() < 1) {            defaultBuildHTML(sb, statusCode, message, report, throwable);        }        try {            try {                response.setContentType("text/html");                response.setCharacterEncoding("utf-8");            } catch (Throwable t) {                if (container.getLogger().isDebugEnabled())                    container.getLogger().debug("status.setContentType", t);            }            Writer writer = response.getReporter();            if (writer != null) {                // If writer is null, it‘s an indication that the response has                // been hard committed already, which should never happen                writer.write(sb.toString());            }        } catch (IOException e) {            ;        } catch (IllegalStateException e) {            ;        }    }    private void defaultBuildHTML(StringBuffer sb, int statusCode,            String message, String report, Throwable throwable) {        sb.append("<html><head><title>");        sb.append(ServerInfo.getServerInfo()).append(" - ");        sb.append(sm.getString("errorReportValve.errorReport"));        sb.append("</title>");        sb.append("<style><!--");        sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS);        sb.append("--></style> ");        sb.append("</head><body>");        sb.append("<h1>");        sb.append(                sm.getString("errorReportValve.statusHeader", "" + statusCode,                        message)).append("</h1>");        sb.append("<HR size=\"1\" noshade=\"noshade\">");        sb.append("<p><b>type</b> ");        if (throwable != null) {            sb.append(sm.getString("errorReportValve.exceptionReport"));        } else {            sb.append(sm.getString("errorReportValve.statusReport"));        }        sb.append("</p>");        sb.append("<p><b>");        sb.append(sm.getString("errorReportValve.message"));        sb.append("</b> <u>");        sb.append(message).append("</u></p>");        sb.append("<p><b>");        sb.append(sm.getString("errorReportValve.description"));        sb.append("</b> <u>");        sb.append(report);        sb.append("</u></p>");        if (throwable != null) {            String stackTrace = getPartialServletStackTrace(throwable);            sb.append("<p><b>");            sb.append(sm.getString("errorReportValve.exception"));            sb.append("</b> <pre>");            sb.append(RequestUtil.filter(stackTrace));            sb.append("</pre></p>");            int loops = 0;            Throwable rootCause = throwable.getCause();            while (rootCause != null && (loops < 10)) {                stackTrace = getPartialServletStackTrace(rootCause);                sb.append("<p><b>");                sb.append(sm.getString("errorReportValve.rootCause"));                sb.append("</b> <pre>");                sb.append(RequestUtil.filter(stackTrace));                sb.append("</pre></p>");                // In case root cause is somehow heavily nested                rootCause = rootCause.getCause();                loops++;            }            sb.append("<p><b>");            sb.append(sm.getString("errorReportValve.note"));            sb.append("</b> <u>");            sb.append(sm.getString("errorReportValve.rootCauseInLogs",                    ServerInfo.getServerInfo()));            sb.append("</u></p>");        }        sb.append("<HR size=\"1\" noshade=\"noshade\">");        sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");        sb.append("</body></html>");    }    private void buildHTMLFromErrorPage(StringBuffer buffer) throws IOException {        InputStream in=null;        Scanner scanner = null;        try {            // 優先從當前路徑下尋找檔案            in=this.getClass().getResourceAsStream(ERROR_PAGE_NAME);            if(in==null){                // 從當前jar包內的根目錄 或者tomcat/lib目錄下                in=Thread.currentThread().getContextClassLoader().getResourceAsStream(ERROR_PAGE_NAME);            }            if(in==null){                in=ClassLoader.getSystemResourceAsStream(ERROR_PAGE_NAME);            }            scanner = new Scanner(in);            while (scanner.hasNextLine()) {                String line = scanner.nextLine();                // line=RequestUtil.filter(line);                buffer.append(line);            }        } catch (Exception ex) {        } finally {            if (scanner != null) {                scanner.close();            }            if(in!=null){                in.close();            }        }    }    }

 

Tomcat:Custom a common error page valve for all web application in tomcat

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.