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 error 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
Servlet error handler package com.ack.web.servlet; 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> <error-code>404</error-code> <location>/servlet/com.ack.web.servlet.ServletErrorHandler</location> </error-page> </web-app> */ public class ServletErrorHandler extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { res.setContentType( "text/html" ); PrintWriter pw = res.getWriter(); String statusCode = getRequestAttribute( req, "javax.servlet.error.status_code", "status code not supplied" ); String errorMsg = getRequestAttribute( req, "javax.servlet.error.message", "error msg not supplied" ); pw.println( "<h1>Error Code: " + statusCode + "</h1>" ); pw.println( "<h2>Error Message: " + errorMsg + "</h1>" ); pw.println( "<p>Problem accessing: " + req.getRequestURI() + "</p>" ); 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; } }