リクエストへの属性追加

広告

フォワードなどを行う際に、フォワード先に何か別の情報を合わせて渡すことができます。クライアントから送られてきたリクエストをフォワード先に渡す前に、リクエストに属性を追加することで実現します。

追加する場合には「HttpServletRequest」インターフェースの親である「ServletRequest」インターフェースで定義されている"setAttribute"メソッドを使います。

Stores an attribute in this request. Attributes are reset between requests. 
This method is most often used in conjunction with RequestDispatcher. 

Attribute names should follow the same conventions as package names. Names 
beginning with java.*, javax.*, and com.sun.*, are reserved for use by 
Sun Microsystems. 
If the object passed in is null, the effect is the same as calling 
removeAttribute(java.lang.String). 
It is warned that when the request is dispatched from the servlet resides 
in a different web application by RequestDispatcher, the object set by 
this method may not be correctly retrieved in the caller servlet. 

Parameters:
  name - a String specifying the name of the attribute
  o - the Object to be stored

"setAttribute"メソッドを使うことで、リクエストに新しい属性名と値をセットすることができます。

次に追加した属性を取り出す場合です。"getAttribute"メソッドを使います。

Returns the value of the named attribute as an Object, or null if no 
attribute of the given name exists. 

Attributes can be set two ways. The servlet container may set attributes 
to make available custom information about a request. For example, for 
requests made using HTTPS, the attribute 
javax.servlet.request.X509Certificate can be used to retrieve information 
on the certificate of the client. Attributes can also be set 
programatically using setAttribute(java.lang.String, java.lang.Object). 
This allows information to be embedded into a request before a 
RequestDispatcher call. 

Attribute names should follow the same conventions as package names. 
This specification reserves names matching java.*, javax.*, and sun.*. 

Parameters:
  name - a String specifying the name of the attribute 
Returns:
  an Object containing the value of the attribute, or null if the 
    attribute does not exist

"getAttribute"メソッドの引数に属性名を指定すれば、対応する値を取り出すことができます。

利用方法としては下記のようになります。

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

  request.setAttribute("Hantei", "Out");

  String disp = "/forwardtest";
  RequestDispatcher dispatch = request.getRequestDispatcher(disp);

  dispatch.forward(request, response);
}

サンプルプログラム

では簡単に試してみます。

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>dispatchtest</servlet-name>
    <servlet-class>DispatchTest2</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>forwardtest</servlet-name>
    <servlet-class>ForwardTest2</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatchtest</servlet-name>
    <url-pattern>/dispatchtest</url-pattern>
  </servlet-mapping>

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

プログラムは下記の通りです。今回はHTMLファイルからフォームを使ってサーブレットへ送信するテストを行いますので、一番最初に呼び出すHTMLファイルをまず用意します。

forwardtest.html

<html>
<head>
<title>フォワードテスト</title>
</head>
<body>

<form action="/dispatch/dispatchtest" method="post">

<table border="0">

<tr>
<td>年齢</td><td><input type="text" size="10" value="" name="toshi"></td>
</tr>
<tr>
<td>年収</td><td><input type="text" size="10" value="" name="nensyu"></td>
</tr>
<tr>
<td>性別</td><td><select name="seibetsu">
<option>男性</option>
<option>女性</option>
</select></td>
</tr>
<tr>

</table>

<input type="submit" VALUE="送信する">
<input type="reset" VALUE="リセット">
</form>

</body>
</html>

次にフォームから呼び出されれるサーブレットです。

DispatchTest2.java

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

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

    response.setContentType("text/html; charset=Shift_JIS");
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("Shift-JIS");

    String[] nensyu = request.getParameterValues("nensyu");
    int nensyu_val = Integer.parseInt(nensyu[0]);

    if (nensyu_val < 2000000){
      request.setAttribute("hantei", "貧乏ですね");
    }else{
      request.setAttribute("hantei", "大丈夫でしょう");
    }

    String disp = "/forwardtest";
    RequestDispatcher dispatch = request.getRequestDispatcher(disp);
    dispatch.forward(request, response);
  }
}

次にフォワード先であるサーブレットです。

ForwardTest2.java

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

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

    response.setContentType("text/html; charset=Shift_JIS");
    PrintWriter out = response.getWriter();
    request.setCharacterEncoding("Shift-JIS");

    out.println("<html>");
    out.println("<head>");
    out.println("<title>ディスパッチ</title>");
    out.println("</head>");
    out.println("<body>");

    String[] toshi = request.getParameterValues("toshi");
    String[] nensyu = request.getParameterValues("nensyu");

    String hantei = (String)request.getAttribute("hantei");

    out.println("<p>");
    out.println("年齢:" + toshi[0] + ", 年収" + nensyu[0]);
    out.println("</p>");

    out.println("<p>");
    out.println("年収判定:" + hantei);
    out.println("</p>");

    out.println("</body>");
    out.println("</html>");
  }
}

上記をコンパイル後に「d:\servlet-sample\dispatch\WEB-INF\classes\」ディレクトリにクラスファイルを移動した後で、ブラウザで「http://localhost:8080/dispatch/forwardtest.html」へアクセスしてみます。

新しい属性の追加

HTMLのフォームが表示されますので適当な値を入力して「送信する」ボタンをクリックして下さい。

新しい属性の追加

まずフォームで指定されたサーブレット内で、年収の入力値から簡単な判定処理をして、その結果を表すメッセージを追加の属性としてセットしてフォワードしています。フォワード先では追加された属性から値を取り出して表示しています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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