「Java開発」ServletのError/Exceptionメッセージを処理するサンプル
Javaコード:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ErrorHandler extends HttpServlet {
// GETリクエスト
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Throwable throwable = (Throwable)
request.getAttribute(“javax.servlet.error.exception");
Integer statusCode = (Integer)
request.getAttribute(“javax.servlet.error.status_code");
String servletName = (String)
request.getAttribute(“javax.servlet.error.servlet_name");
if (servletName == null){
servletName = “Unknown";
}
String requestUri = (String)
request.getAttribute(“javax.servlet.error.request_uri");
if (requestUri == null){
requestUri = “Unknown";
}
// コンテンツタイプ
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
String title = " Error/Exception 情報";
String docType = “<!DOCTYPE html>\n";
out.println(docType +
“<html>\n" +
“<head><title>" + title + “</title></head>\n" +
“<body bgcolor=\"#f0f0f0\">\n");
out.println(“<h1>sample for request </h1>");
if (throwable == null && statusCode == null){
out.println(“<h2>erroe message</h2>");
out.println(" <a href=\"" +
response.encodeURL(“http://localhost:8080/") +
“\">ホームページ</a>。");
}else if (statusCode != null) {
out.println(“エラーコード : " + statusCode);
}else{
out.println(“<h2>エラーメッセージ</h2>");
out.println(“Servlet Name : " + servletName +
“</br></br>");
out.println(“エラークラス名 : " +
throwable.getClass( ).getName( ) +
“</br></br>");
out.println(" URI: " + requestUri +
“<br><br>");
out.println(“メッセージ: " +
throwable.getMessage( ));
}
out.println(“</body>");
out.println(“</html>");
}
// postリクエスト
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}