URLパターン(パスマッピング)

広告

次はワイルドカードを使った記述方法です。特定のパスに含まれる全てのファイルへマッピングを行います。

例えば"HelloWorld.class"というクラスに対して、"hello"というサーブレット名を付けます。そして「/hello/」で始まるURLが呼ばれた場合にこのサーブレットが呼び出されるようにしてみます。

<web-app>
  <servlet>
    <servlet-name>
      hello
    </servlet-name>
    <servlet-class>
      HelloWorld
    </servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>
      hello
    </servlet-name>
    <url-pattern>
      /hello/*
    </url-pattern>
  </servlet-mapping>
</web-app>

この場合、「http://localhost:8080/webxmltest/hello/」から始まる全ての呼び出しに対して指定のサーブレットを実行します。例えば下記のどの呼び出し方をしても同じサーブレットが呼び出されます。

http://localhost:8080/webxmltest/hello/hellowolrd
http://localhost:8080/webxmltest/hello/index.html
http://localhost:8080/webxmltest/hello/sub/sub2/exsample.jpg

※Webアプリケーションのパスを「webxmltest」としています。

複数のファイルを1つのサーブレットで処理するメリットとしては、例えば「/print/」が付くようなサーブレットを呼び出した場合は必ず印刷用の特定のサーブレットが呼ばれ、そのサーブレットの中で実際に呼び出されたURLから何のファイルが対象としているかを判別した上で処理するような利用方法などが考えられます。

サンプル

では一度試してみます。

web.xml

※上記は同じ名前のファイルを使う関係でリンク先には「web3.xml」というファイルがリンクされています。実際に使う時には「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>hello1</servlet-name>
    <servlet-class>HelloWorld1</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>hello2</servlet-name>
    <servlet-class>HelloWorld2</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello1</servlet-name>
    <url-pattern>/hello/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>hello2</servlet-name>
    <url-pattern>/abc/def/*</url-pattern>
  </servlet-mapping>
</web-app>

作成した「web.xml」をWebアプリケーションのディレクトリの中の「WEB-INF」ディレクトリに配置します。

また実際に呼び出すサーブレットとして下記の2つのファイルをコンパイルし、Webアプリケーションのディレクトリの中の「WEB-INF\classes」ディレクトリに配置します。

HelloWorld1.java

HelloWorld2.java

では実際にサーブレットを呼び出して見ます。

http://localhost:8080/webxmltest/hello/abc

上記のように呼び出すと「HelloWorld1.class」が呼び出されて下記のように表示されます。

URLパターン

呼び出しの先頭が「http://localhost:8080/webxmltest/hello/」であれば、全て同じサーブレットを呼び出しますので、例えば下記のように呼び出しても同じサーブレットが呼び出されます。

http://localhost:8080/webxmltest/hello/doc/sample.html

結果は同じように下記のようになります。

URLパターン

次にもう1つの方のサーブレットを呼び出してみます。例えば下記のような呼び出しとなります。

http://localhost:8080/webxmltest/abc/def/hello

上記のように呼び出すと「HelloWorld2.class」が呼び出されて下記のように表示されます。

URLパターン

こちらの場合は呼び出しの先頭が「http://localhost:8080/webxmltest/abc/def/」であれば、全て同じサーブレットを呼び出します。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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