Java/Servlets/Exception

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Exceptions in Servlet

/*
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.ru/xml/ns/j2ee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee
         http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <servlet>
    <servlet-name>DeliberateException</servlet-name>
    <servlet-class>DeliberateException</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DeliberateException</servlet-name>
    <url-pattern>/deliberateException</url-pattern>
  </servlet-mapping>
</web-app>
*/
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DeliberateException extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    throw new NullPointerException();
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    ServletOutputStream out = res.getOutputStream();
    res.setContentType("text/html");
    out.println("<html><head><title>Exception Thrower</title></head>");
    out.println("<body>You"ll never see this!</body></html>");
  }
}





ForwardException - show forwarding an exception to an error page

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/*
 * ForwardException - show forwarding an exception to an error page.
 * 
 * @author  Ian Darwin
 * @version $Id: ForwardException.java,v 1.2 2002/03/13 21:50:30 ian Exp $
 */
public class ForwardException extends HttpServlet
{
  /** Called in response to a GET request (data encoded in the URL) */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    ServletContext application = getServletContext();
    // BOILERPLATE beginning 
    response.setContentType("text/html");
    PrintWriter out = response.getWriter(); 
    try {
      // to do: logic code and main HTML goes here.
      // simulate an error condition happening at run time.
      if (this instanceof Servlet)
        throw new RuntimeException("Test exception");
      out.println("<!DOCTYPE html PUBLIC " +
        "\"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" +
        "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"\n" +
        ">");
      out.println("<html>");
      out.println("<head><title>Servlet Output</title></head>");
      out.println("<body>");
      // BOILERPLATE ending
      out.println("</body>");
      out.println("</html>");
      out.close();
    } catch (Exception exc) {
      // dispatch to JSP to display the error.
      RequestDispatcher rd = application.getRequestDispatcher("/oops.jsp");
      request.setAttribute("javax.servlet.jsp.jspException", exc);
      rd.forward(request, response);
    }
  }
}





javax.servlet.error.request_uri

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;
public class ErrorDisplay extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    String code = null, message = null, type = null, uri = null;
    Object codeObj, messageObj, typeObj;
    Throwable throwable;
    codeObj = req.getAttribute("javax.servlet.error.status_code");
    messageObj = req.getAttribute("javax.servlet.error.message");
    typeObj = req.getAttribute("javax.servlet.error.exception_type");
    throwable = (Throwable) req.getAttribute("javax.servlet.error.exception");
    uri = (String) req.getAttribute("javax.servlet.error.request_uri");
    if (uri == null) {
      uri = req.getRequestURI(); // in case there"s no URI given
    }
    // Convert the attributes to string values
    if (codeObj != null)
      code = codeObj.toString();
    if (messageObj != null)
      message = messageObj.toString();
    if (typeObj != null)
      type = typeObj.toString();
    // The error reason is either the status code or exception type
    String reason = (code != null ? code : type);
    out.println("<HTML>");
    out.println("<HEAD><TITLE>" + reason + ": " + message + "</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<H1>" + reason + "</H1>");
    out.println("<H2>" + message + "</H2>");
    out.println("<PRE>");
    if (throwable != null) {
      throwable.printStackTrace(out);
    }
    out.println("</PRE>");
    out.println("<HR>");
    out.println("<I>Error accessing " + uri + "</I>");
    out.println("</BODY></HTML>");
  }
}