リダイレクトの設定(sendRedirect)

広告

ステータスコードとLocationヘッダーの設定によってURLを転送させる事ができますが、リダイレクト用のメソッドが別途用意されているのでそれを利用することでも他のページへ転送させる事ができます。

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

Sends a temporary redirect response to the client using the specified
redirect location URL. This method can accept relative URLs; the servlet 
container must convert the relative URL to an absolute URL before sending 
the response to the client. If the location is relative without a leading 
'/' the container interprets it as relative to the current request URI. 
If the location is relative with a leading '/' the container interprets 
it as relative to the servlet container root. 

If the response has already been committed, this method throws an
IllegalStateException. After using this method, the response should be 
considered to be committed and should not be written to. 

Parameters:
  location - the redirect location URL 
Throws: 
  java.io.IOException - If an input or output exception occurs 
  java.lang.IllegalStateException - If the response was committed or
    if a partial URL is given and cannot be converted into a valid URL

引数にリダイレクト先のURLを指定します。URLは絶対パスの他に相対パスでの指定も可能です。

「sendRedirect」メソッドを使う場合には次のように記述した場合と同じです。

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

サンプルプログラム

では簡単なサンプルで試して見ます。クライアント側のフォームで指定したURLへリダイレクトするようにします。

リダイレクト先を選択するフォームが含まれるHTMLページは、次のようなものです。

formsample6.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/ResponseSample5" method="get">

<table>
<tr>
<td>リダイレクト先の選択</td>
<td>
<select name="url" size="2">
<option value="www.yahoo.co.jp">YAHOO</option>
<option value="www.google.co.jp">GOOGLE</option>
</select>
</td>
</tr>
</table>
<input type="submit" name="button1" value="送信">
</form>

</body>
</html>

次にフォームから送られてくるリクエストパラメータを処理するサーブレットを作成します。

ResponseSample5.java

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

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

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

    String tmp;

    String url = "";
    tmp = request.getParameter("url");
    if (tmp == null || tmp.length() == 0){
      url = "http://www.excite.co.jp/";
    }else{
      url = "http://" + tmp;
    }

    response.sendRedirect(url);
  }
}

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

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

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

sendRedirect

リダイレクト先を選択して「送信」ボタンをクリックして下さい。「YAHOO」を選択している場合は次のようにYAHOOへリダイレクトされます。

sendRedirect

「GOOGLE」を選択した場合はGOOGLEへリダイレクトされます。

sendRedirect

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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