Java のサーブレットで、HTML のレスポンスを返却する方法を書いていきます。
バージョン
ブログ執筆時の製品バージョンは以下の通りです。
目次
1. サーブレットの作成
HttpServletResponse
を使って、レスポンスを返すクラスを作成します。
org/example/response/HtmlServlet.java
package org.example.response; 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("/res/html") @SuppressWarnings("serial") public class HtmlServlet 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>Hello!</p></body></html>" ); } }
@WebServlet
を付けて、/res/html
のリクエストを処理できるようにしています。
2. ディレクトリ階層の作成
動作確認をする場合、以下のコマンドでプロジェクト sample-servlet
のディレクトリ階層を作成します。
mkdir sample-servlet cd sample-servlet mkdir src\main\java mkdir src\main\webapp\WEB-INF
作成したら、src/main/java
配下にサーブレットのコードを置きます。
3. 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>
Maven でサーブレットコンテナを起動できるように、build
で Jetty Plugin を定義しています。
4. 動作確認
以下のコマンドでコンテナ(Jetty Maven Plugin)を起動します。
sample-servlet> mvn jetty:run
起動後にブラウザで以下の URL を開きます。
http://localhost:8080/res/html
ブラウザで開くと、以下の文字列が表示されます。
Hello!