リクエストパラメータの取得(getParameter)

広告

「HttpServletRequest」インターフェースのオブジェクトからは色々な情報が取り出せますが、一番利用頻度が高いリクエストパラメータの取得方法から見ていきます。リクエストパラメータとはクライアント側のフォームから送られてきたデータです。

リクエストパラメータは「名前」と「値」のペアで送られてきます。GETメソッドとPOSTメソッドの両方で送られてくる可能性がありますが、サーブレットではどちらのHTTPメソッドで送られてきたかを意識せずに処理することが可能です。

getParameterメソッドとgetParameterValuesメソッド

リクエストパラメータを取得するには「HttpServletRequest」インターフェースの親インターフェースである「ServletRequest」インタフェースで定義されている「getParameter」メソッドを使います。

Returns the value of a request parameter as a String, or null if the
parameter does not exist. Request parameters are extra information sent 
with the request. For HTTP servlets, parameters are contained in the 
query string or posted form data. 

You should only use this method when you are sure the parameter has only 
one value. If the parameter might have more than one value, use 
getParameterValues(java.lang.String). 

If you use this method with a multivalued parameter, the value returned 
is equal to the first value in the array returned by getParameterValues. 

Parameters:
  name - a String specifying the name of the parameter 
Returns:
  a String representing the single value of the parameter

リクエストパラメータの「名前」を引数に指定すると「値」を取得することができます。例えば次のように使います。

public class Sample extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException{

    String val = request.getParameter("name");
  }
}

また1つの「名前」に対して複数の「値」が送られてくるとがあります。その場合「getParameter」メソッドでは「値」の中の最初のものだけを取得することができます。全ての「値」を取得するには「getParameterValues」メソッドを使います。

Returns an array of String objects containing all of the values the given 
request parameter has, or null if the parameter does not exist. 

If the parameter has a single value, the array has a length of 1. 

Parameters:
  name - a String containing the name of the parameter whose value 
    is requested 
Returns:
  an array of String objects containing the parameter's values

リクエストパラメータの「名前」を引数に指定すると「名前」に対応する「値」を全て取得することができます。

例えば取得した値を全て出力するような場合には次のように記述します。

public class Sample extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException{

    String vals[] = request.getParameterValues("name");
    if (vals != null){
      for (int i = 0 ; i < vals.length ; i++){
        out.println(vals[i]);
      }
    }
  }
}

取得する値

リクエストパラメータに対して、送られてきていない「名前」を指定して「値」を取得しようとすると、「値」には「null」が含まれます。またクライアント側のフォームではJavaScriptなどを利用してチェックしていない限り、値が設定されていなかったり想定しているものとは違う値が含まれている可能性がありますので注意が必要です。

また取得できる値は全てString型の値となります。必要であれば数値型に別途変換して下さい。

次の例ではパラメータの値を取得したあと、「null」や空の値であった場合は「-1」を設定し、そうでなければint型の値に変換しています。変換の時にも数値に変換できない値であった場合には「-1」を設定しています。

public class Sample extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException{

    int num;
    String pram = request.getParameter("name");

    if (param == null || param.length() == 0){
      num = -1;
    }else{
      try{
        num = Integer.parseInt(param);
      }catch (NumberFormatException e){
        num = -1;
      }
    }
  }
}

サンプルプログラム

では簡単なサンプルで試して見ます。

まずはフォームが含まれるHTMLページを作成します。フォームの送信先は今回作成する「/sample/RequestSample1」です。

formsample.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="ja">
<head>
<meta http-equiv="Content-Type" Content="text/html;charset=Shift_JIS">
<title>フォームサンプル</title>
</head>
<body>

<p>アンケート調査です</p>

<form action="/sample/RequestSample1" method="get">

<table>
<tr>
<td>氏名</td>
<td><input type="text" size="20" value="" name="name"></td>
</tr>
<tr>
<td>年齢</td>
<td><input type="text" size="5" value="" name="old"></td>
</tr>
<tr>
<td>好きな果物</td>
<td>
<select name="food" size="3" multiple>
<option value="apple">りんご</option>
<option value="melon">メロン</option>
<option value="grape">ぶどう</option>
</select>
</td>
</tr>
</table>
<input type="submit" name="button1" value="送信">
</form>

</body>
</html>

次にフォームから送られてくるリクエストパラメータを処理するサーブレットを作成します。今回は受け取った値を表示するだけです。

RequestSample1.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestSample1 extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException{

    response.setContentType("text/html;charset=Shift_JIS");
    PrintWriter out = response.getWriter();

    String name = request.getParameter("name");

    int old;
    String tmp = request.getParameter("old");
    if (tmp == null || tmp.length() == 0){
      old = -1;
    }else{
      try{
        old = Integer.parseInt(tmp);
      }catch (NumberFormatException e){
        old = -1;
      }
    }

    String food[] = request.getParameterValues("food");

    StringBuffer sb = new StringBuffer();

    sb.append("<html>");
    sb.append("<head>");
    sb.append("<title>サンプル</title>");
    sb.append("</head>");
    sb.append("<body>");

    sb.append("<p>お名前は ");
    sb.append(name);
    sb.append(" です</p>");

    sb.append("<p>年齢は ");
    if (old == -1){
      sb.append("未設定です</p>");
    }else{
      sb.append(old);
      sb.append(" です</p>");
    }

    sb.append("<p>好きな果物は ");
    if (food != null){
      for (int i = 0 ; i < food.length ; i++){
        sb.append(food[i]);
        sb.append(" ");
      }

      sb.append(" です</p>");
    }else{
      sb.append("選択されていません</p>");
    }

    sb.append("</body>");
    sb.append("</html>");

    out.println(new String(sb));

    out.close();
  }
}

サンプルプログラムをコンパイルして作成した「RequestSample1.class」ファイルを別途作成した「web.xml」ファイルを次のように配置します。

D:\ -- servlet-sample
        |
        +-- (formsample.html)
        |
        +-- WEB-INF
             |
             +-- (web.xml)
             |
             +-- classes
                  |
                  +-- (RequestSample1.class)

web.xmlファイルは次のようになります。

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">

  <servlet>
    <servlet-name>RequestSample1</servlet-name>
    <servlet-class>RequestSample1</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>RequestSample1</servlet-name>
    <url-pattern>/RequestSample1</url-pattern>
  </servlet-mapping>
</web-app>

コンテキストファイルを作成し「(Tomcatをインストールしたディレクトリ)\Tomcat 5.5\conf\Catalina\localhost\」ディレクトリに「sample.xml」ファイルとして保存します。内容は以下の通りです。

<Context path="/sample"
docBase="d:/servlet-sample/sample">
</Context>

準備は以上です。ではTomcatを再起動してから「http://localhost:8080/sample/formsample.html」へブラウザでアクセスして下さい。

リクエストパラメータの取得

フォームが表示されますので、適当に値を入力して下さい。

リクエストパラメータの取得

入力したら送信ボタンをクリックします。すると次のようにリクエストパラメータの値を取得して表示します。

リクエストパラメータの取得

今回は「GET」メソッドを使いましたが「POST」メソッドを使った場合は「doPost」メソッド内にまったく同じプログラムを記述すれば大丈夫です。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。