サーブレットのURLパターンと、静的コンテンツ(HTMLなど)のパスが同じ場合、どちらが優先されるのかを確認してみました。
バージョン
動作確認のために、以下の製品を使用しました。
目次
1. 検証結果
Jetty 11(Servlet 5.0)の場合、サーブレットが優先されました。
以下の資源を使って、サーブレットのレスポンスが返ってくることを確認しました。
2. サーブレットの作成
動作確認のため、以下のサーブレットを作成しました。
src/main/java/org/example/IndexServlet.java
package org.example; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet("/index.html") @SuppressWarnings("serial") public class IndexServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); res.setCharacterEncoding("utf-8"); res.getWriter().println( "<html><body><p>Servlet</p></body></html>" ); } }
URL を index.html にしています。
3. HTMLの作成
以下の HTML を作成しました。
src/main/webapp/index.html
<!DOCTYPE html> <html> <head><meta charset="utf-8"></head> <body> <p>HTML</p> </body> </html>
4. ディレクトリ階層の作成
以下のコマンドで、プロジェクト sample-servlet
のディレクトリ階層を作成します。
mkdir sample-servlet cd sample-servlet mkdir src\main\java mkdir src\main\webapp\WEB-INF
作成したら、src/main/java
配下にサーブレットを置きます。HTML は src/main/webapp
の下に置きます。
5. pom.xml の作成
フォルダ sample-servlet
に pom.xml
を作成します。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>sample-servlet</artifactId> <version>1.0.0</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.4.0</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>11.0.15</version> <configuration> <scan>1</scan> </configuration> </plugin> </plugins> </build> </project>
サーブレットコンテナを起動できるように、build
で Jetty Plugin を定義しています。
6. 動作確認
以下のコマンドでコンテナを起動します。
sample-servlet> mvn jetty:run
ブラウザで、以下の URL を開きます。
http://localhost:8080/index.html
以下の文言が表示されることを確認しました。
Servlet