リクエストURIの取得(getRequestURI)

広告

サーブレットが呼ばれた時のURIを取得する方法を確認します。(ただし、ここでURIやURLと読んでいるものは一般的に言われている厳密なものとは若干異なります)。

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

Returns the part of this request's URL from the protocol name up to the 
query string in the first line of the HTTP request. The web container 
does not decode this String. For example:

  First line of HTTP request           Returned Value
  ------------------------------------------------------
  POST /some/path.html HTTP/1.1        /some/path.html
  GET http://foo.bar/a.html HTTP/1.0   /a.html
  HEAD /xyz?a=b HTTP/1.1               /xyz

To reconstruct an URL with a scheme and host, use 
HttpUtils.getRequestURL(javax.servlet.http.HttpServletRequest). 

Returns:
  a String containing the part of the URL from the protocol name up
    to the query string

このメソッドでは、リクエストに含まれるポート番号とパラメータの間の部分を取得できます。つまりコンテキストパス+サーブレットパスの部分です。

またリクエストの中のサーブレット名だけを知りたい場合には「getServletPath」メソッドを使います。

Returns the part of this request's URL that calls the servlet. This path 
starts with a "/" character and includes either the servlet name or a 
path to the servlet, but does not include any extra path information or 
a query string. Same as the value of the CGI variable SCRIPT_NAME. 

This method will return an empty string ("") if the servlet used to process 
this request was matched using the "/*" pattern. 

Returns:
  a String containing the name or path of the servlet being called, as 
    specified in the request URL, decoded, or an empty string if the servlet 
    used to process the request is matched using the "/*" pattern.

このメソッドではサーブレットパスの部分でけを取得できます。

またURLそのものを取得したい場合には「getRequestURL」メソッドを使います。

Reconstructs the URL the client used to make the request. The returned 
URL contains a protocol, server name, port number, and server path, but 
it does not include query string parameters. 

Because this method returns a StringBuffer, not a string, you can modify 
the URL easily, for example, to append query parameters. 

This method is useful for creating redirect messages and for reporting 
errors. 

Returns:
  a StringBuffer object containing the reconstructed URL

このメソッドの場合はURL形式で取得ができます。ただし、このメソッドでもクエリー文字列のパラメータ部分は取得されません。また戻り値がStringBufferクラスのオブジェクトになっていますので注意が必要です。

サンプルプログラム

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

今回はサーブレットを直接呼び出してリクエストから各種情報を取り出してみます。

RequestSample5.java

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

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

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

    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("getRequestURL:");
    sb.append(new String(request.getRequestURL()));
    sb.append("</p>");

    sb.append("<p>");
    sb.append("getRequestURI:");
    sb.append(request.getRequestURI());
    sb.append("</p>");

    sb.append("<p>");
    sb.append("getServletPath:");
    sb.append(request.getServletPath());
    sb.append("</p>");

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

    out.println(new String(sb));

    out.close();
  }
}

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

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

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

getRequestURI

呼び出されたリクエストからサーブレット名を取り出して自動的にリンク先を作成する場合などに使います。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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