Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Servlets Code Examples

Servlet exception handler

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
Servlet exception handler package com.ack.web.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Map the location of the servlet to handle at error * with the supplied status code * <web-app> ... <error-page> <exception-type>javax.servlet.ServletException</exception-type> <location>/servlet/com.ack.web.servlet.ServletExceptionHandler</location> </error-page> </web-app> */ public class ServletExceptionHandler extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { res.setContentType( "text/html" ); PrintWriter pw = res.getWriter(); String exceptionType = getRequestAttribute( req, "javax.servlet.error.exception_type", "status code not supplied" ); String errorMsg = getRequestAttribute( req, "javax.servlet.error.message", "error msg not supplied" ); // exception attribute available as of servlet 2.3 API Object exception = req.getAttribute( "javax.servlet.error.exception" ); pw.println( "<h1>Custom Exception Handler</h1>" ); pw.println( "<h2>Exception type: " + exceptionType + "</h1>" ); pw.println( "<h2>Exception Message: " + errorMsg + "</h1>" ); pw.println( "<p>Problem accessing: " + req.getRequestURI() + "</p>" ); // if we have the exception dump it out to the page if( exception != null ) { ByteArrayOutputStream bos = null; try { pw.println( "<p><hr noshade><p><pre>" ); bos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter( bos, true ); ( (Exception) exception ).printStackTrace( writer ); pw.println( bos.toString() ); } finally { pw.println( "</pre>" ); if( bos != null ) bos.close(); } } // output date and time of error pw.println( "<p><hr><p>" ); pw.println( new java.util.Date( System.currentTimeMillis() ) ); } private String getRequestAttribute( HttpServletRequest req, String name, String defaultValue ) { Object value = req.getAttribute( name ); return ( value != null ) ? value.toString() : defaultValue; } }