Tomcat:custom a common error page valve for all Web application in Tomcat

Source: Internet
Author: User
Tags tomcat server

If you deploy multiple Web apps on a single Tomcat server, and you want these web apps to share a set of error pages instead of using the default error page. You will need to customize the error page.

Error pages can be configured through Error-page in each Web application. But when you have multiple Web apps, it's a bit of a hassle to configure an error page in each of your apps ' Web. Xml. However, it is not possible to configure the error page in Tomcat/conf/web.xml. Because Tomcat deploys the application, it merges the public Web. XML with the website. XML for each application, looking for the page in the directory of each Web app.

To achieve a common directory, you can only rewrite the default implementation of Tomcat yourself. Fortunately, Tomcat is supporting us in this way.

 Packagecom.fjn.frame.catalina.valves;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.Writer;ImportJava.util.Scanner;Importorg.apache.catalina.connector.Request;ImportOrg.apache.catalina.connector.Response;ImportOrg.apache.catalina.util.RequestUtil;ImportOrg.apache.catalina.util.ServerInfo;ImportOrg.apache.catalina.valves.ErrorReportValve;/*** * To use this class to customize the error page, you need to adjust the Errorreportvalveclass property value of the host in Server.xml to this class. * Also need to put this class into a jar package in the Tomcat/lib directory. * @sinceTomcat 6.0 *@author[email protected] June 4, 2015 **/ Public classErrorpagevalveextendsErrorreportvalve {Private Static FinalString error_page_name = "errorpage.html"; @Overrideprotected voidReport (Request request, Response Response, Throwable throwable) {//Do nothing on non-http responses        intStatusCode =Response.getstatus (); //Do nothing on a 1xx, 2xx and 3xx status//Do nothing If anything have been written already        if(StatusCode < | | 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 (NewScanner (Exceptionmessage)). nextline ()); }            }            if(Message = =NULL) {Message= ""; }        }        //Do nothing if there are no report for the specified status codeString report =NULL; Try{ Report= Sm.getstring ("http." +StatusCode); } Catch(Throwable t) {; }        if(Report = =NULL)            return; StringBuffer SB=NewStringBuffer (); 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 the response have//been hard committed already, which should never happenWriter.write (sb.tostring ()); }        } Catch(IOException e) {; } Catch(IllegalStateException e) {; }    }    Private voidDefaultbuildhtml (StringBuffer SB,intStatusCode, String message, String report, Throwable throwable) {Sb.append ("); 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 ("); Sb.append ("); Sb.append (Sm.getstring ("Errorreportvalve.statusheader", "" "+statusCode, message)). Append ("); Sb.append ("); 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>"); intLoops = 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 nestedRootcause =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 ("); Sb.append ("); Sb.append ("</body>); }    Private voidBuildhtmlfromerrorpage (StringBuffer buffer)throwsIOException {InputStream in=NULL; Scanner Scanner=NULL; Try {            //prefer to find files from the current pathin= This. GetClass (). getResourceAsStream (Error_page_name); if(in==NULL){                //from the root directory in the current jar package or under the Tomcat/lib directoryin=Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (Error_page_name); }            if(in==NULL) { in=Classloader.getsystemresourceasstream (error_page_name); } Scanner=NewScanner (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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.