ヘッダーの設定(setHeader)

広告

クライアントにレスポンスを返す際にヘッダーを新規に追加したり上書きしたりすることができます。

ヘッダーを設定するには「HttpServletResponse」インターフェースで定義されている「setHeader」メソッドを使います。

Sets a response header with the given name and value. If the header had 
already been set, the new value overwrites the previous one. The 
containsHeader method can be used to test for the presence of a header 
before setting its value. 

Parameters:
  name - the name of the header
  value - the header value If it contains octet string, it should be
    encoded according to RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt)

引数には設定したいヘッダー名と対応する値を指定します。既に同じヘッダー名が設定されていた場合は上書きされます。

サンプルプログラム

では簡単なサンプルで試して見ます。ページが他へ移動したことを表すスタータスコード「SC_MOVED_PERMANENTLY」を設定した場合に、新しい場所を表す「Locationo」ヘッダーを設定してみます。

ResponseSample4.java

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

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

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

    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader("Location", "http://www.yahoo.co.jp/");

    StringBuffer sb = new StringBuffer();

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

    sb.append("<p>移動しました</p>");

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

    out.println(new String(sb));
    out.close();
  }
}

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

D:\ -- servlet-sample
        |
        +-- WEB-INF
             |
             +-- (web.xml)
             |
             +-- classes
                  |
                  +-- (ResponseSample4.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>ResponseSample4</servlet-name>
    <servlet-class>ResponseSample4</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ResponseSample4</servlet-name>
    <url-pattern>/ResponseSample4</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/ResponseSample4」へブラウザでアクセスして下さい。

setHeader

今回は「Location」ヘッダーを設定していますので、ヘッダーに設定したURLに転送されます。結果的にYahooのページが表示されます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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