HttpRequestDumpサーブレットで要求オブジェクトの内容を知る

 


それではHttpRequestDumpというサーブレットのプログラム・リストを以下に記すので、これを各自コピー(インポート)して自分のbasic_servletsパッケージに追加して走らせて見ていただきたい。Tomcatの環境の読者は、最初のpackage宣言の行の削除、及び赤で示した箇所の変更とを行ってからコンパイルを行う必要がある。

 

package basic_servlets;

 

import java.io.*;

import java.lang.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.security.*;

 

/**

 * HttpRequestDumpは、HTTP要求オブジェクトをクライアントに返す。

 * 作成日 : (01/05/14 15:25:35)

 * @author: Terry

 */

public class HttpRequestDump extends HttpServlet {

/**

 * Process incoming HTTP GET requests

 */

public void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {

    performTask(request, response);

}

/**

 * Process incoming HTTP POST requests

 */

public void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {

    performTask(request, response);

}

/**

 * 本サーブレット情報の文字列を返す。

 */

public String getServletInfo() {

    return "HttpRequestDump, Version 1.0 by Terry";

}

/**

 * ダンプ処理の実体。

 * 作成日 : (01/05/14 15:35:19)

 */

public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

  response.setContentType("text/html; charset=Shift_JIS");  //応答ヘッダContent-Type追加

  PrintWriter out = response.getWriter();                   //出力バッファ取得

 

  dumpRequest(request, response, out);                      //ダンプ処理のメソッドを呼ぶ

 

 

  out.println("</PRE></BODY></HTML>");                      //HTMLフッタの出力

  out.flush();                                              //バッファの明示的吐き出し

  out.close();                                              //バッファの明示的クローズ

}

 

/**

 * ダンプ処理の実体。

 * 作成日 : (01/05/14 15:35:19)

 * @param request javax.servlet.http.HttpServletRequest

 * @param response javax.servlet.http.HttpServletResponse

 * @param out java.io.PrintWriter

 */

public void dumpRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {

  // HTMLヘッダの出力

  out.println("<HTML><HEAD><TITLE>");

  out.println("要求オブジェクトの情報");

  out.println("</TITLE></HEAD>");

 

  // HTMLボディの出力

  out.println("<BODY><H1>要求オブジェクトの情報</H1><PRE>");

 

  out.println("getAuthType: " + request.getAuthType());

  out.println("getCharacterEncoding: " + request.getCharacterEncoding());

  out.println("getContentLength: " + request.getContentLength());

  out.println("getContentType: " + request.getContentType());

  out.println("getMethod: " + request.getMethod());

  //out.println("getLocale: " + request.getLocale().toString()); //VisualAgeにはまだ組み込まれていない

  out.println("getPathInfo: " + request.getPathInfo());

  out.println("getPathTranslated: " + request.getPathTranslated());

  out.println("getProtocol: " + request.getProtocol());

  out.println("getQueryString: " + request.getQueryString());

  out.println("getRemoteAddr: " + request.getRemoteAddr());

  out.println("getRemoteHost: " + request.getRemoteHost());

  out.println("getRemoteUser: " + request.getRemoteUser());

  out.println("getRequestURI: " + request.getRequestURI());

  out.println("getRequestedSessionId: " + request.getRequestedSessionId());

  out.println("isRequestedSessionIdValid: " + (new Boolean(request.isRequestedSessionIdValid())).toString());

  out.println("isRequestedSessionIdFromCookie: " + (new Boolean(request.isRequestedSessionIdFromCookie())).toString());

  out.println("isRequestedSessionIdFromURL: " + (new Boolean(request.isRequestedSessionIdFromURL())).toString());

  out.println("getScheme: " + request.getScheme());

  //out.println("isSecure: " + (new Boolean(request.isSecure())).toString()); //VisualAgeにはまだ組み込まれていない

  out.println("getServerName: " + request.getServerName());

  out.println("getServerPort: " + request.getServerPort());

  ServletContext context = getServletContext();

  out.println("getRealPath: " + context.getRealPath(request.getRequestURI()));

  out.println("getServletPath: " + request.getServletPath());

  out.println("getContextPath: " + request.getContextPath()); //VisualAgeにはまだ組み込まれていない

 

  out.println();

  out.println("要求パラメタ:");

  Enumeration paramNames = request.getParameterNames();

  while (paramNames.hasMoreElements()) {

    String name = (String) paramNames.nextElement();

    String[] values = request.getParameterValues(name);

    out.println("    " + name + ":");

    for (int i = 0; i < values.length; i++) {

 

  out.println("      " + values[i]);

//  Tomcatの場合は上の1行は以下の6行のように変更すること

//  TomcatはURLエンコードされているパラメタのコードが標準のISO8859_1(Latin-1)であると仮定し

//  それを単にStringに(つまりUnicodeで)格納して各サーブレットに引き渡している。

//  したがってそのためパラメタ文字列を取得する際にはISO8859_1から自分が期待する

//  エンコードへの変換をしなければならない。

//    try{

//        String correctValue = new String(values[i].getBytes("8859_1"), "Shift_JIS");

//        out.println("      " + correctValue);

//    }catch(UnsupportedEncodingException theException){

//        out.println("UnsupportedExceptionの例外が発生");

//    }

    }

  }

 

  out.println();

  out.println("要求ヘッダのダンプ:");

  Enumeration headerNames = request.getHeaderNames();

 

  while (headerNames.hasMoreElements()) {

    String name = (String) headerNames.nextElement();

    String value = request.getHeader(name);

 

    out.println("  " + name + " : " + value);

//  この個所もTomcatの場合以下の6行のように適用される

//  try{

//    String correctValue = new String(value.getBytes("8859_1"), "Shift_JIS");

//    out.println("  " + name + " : " + correctValue);

//  }catch(UnsupportedEncodingException theException){

//    out.println("UnsupportedExceptionの例外が発生");

//  }

    }

 

 

  out.println();

  out.println("属性(Attributes):");

  Enumeration attributeNames = request.getAttributeNames();

  while (attributeNames.hasMoreElements()) {

    String name = (String) attributeNames.nextElement();

    Object value = request.getAttribute(name);

    out.println("  " + name + " : " + value.toString());

  }

 

  out.println();

  out.println("クッキー(Cookies):");

  Cookie[] cookies = request.getCookies();

  if (cookies.length > 0) {

    for (int i = 0; i < cookies.length; i++) {

        String name = cookies[i].getName();

        String value = cookies[i].getValue();

        out.println("  " + name + " : " + value);

    }

  }

  out.println();

  out.println("*** 以上 ***");

   

}

}

 

このプログラムの注意点:

1)              サーブレットのAPIは、HTTP要求がGET(URLにクエリとして要求パラメタが含められる)でもPOST(要求パラメタがHTTP要求パケットのボディ部分に含められる)でも同じメソッドで要求パラメタが取り出せるよう用意されている。従って、サーブレットはGETとPOSTを意識することなく記述できる。そのため、doGetやdoPostのメソッドごとにオーバライドするのではなく、ひとつのメソッド(例えばperformTaskという名前で)集約させるのが一般的である。なお、到来要求毎に生成されたスレッドは、serviceというメソッドに入り、そこでdoGetなどのメソッドに分岐する。それをまたperformTaskというメソッドにPostとGetの処理をまとめることになる。

 

 

 

 

 

前節     目次     次節