Java のサーブレットで、JSON のレスポンスを返却する方法を書いていきます。
バージョン
ブログ執筆時の製品バージョンは以下の通りです。
1. サーブレットの作成
以下のプログラムを作成します。
src/main/java/org/sample/HelloServlet.java
package org.sample; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; @WebServlet("/hello") public class HelloServlet extends HttpServlet { private static final ObjectMapper OM = new ObjectMapper(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String json = OM.writeValueAsString( Map.of("message", "こんにちは。") ); res.setContentType("application/json"); res.getWriter().print(json); } }
Jackson Dtabind で JSON を生成しています。
2. 動作確認
サーブレットコンテナを起動して、以下の URL にアクセスします。
http://localhost:8080/hello
レスポンスは以下の通りになります。
{"message":"こんにちは。"}
3. 文字コードについて
レスポンスのエンコーディングは、以下のメソッドで設定できます。
res.setCharacterEncoding("エンコーディング名");
最近のブラウザは、エンコーディングが指定されていないと、UTF-8 がデフォルトになるようです。
Spring Boot も、JSON のレスポンスにエンコーディングを設定していませんでした。
4. ビルドファイルについて
Maven のビルドファイルは以下の通りです。
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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.sample</groupId> <artifactId>servlet-json</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> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.1</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.3.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>11.0.12</version> <configuration> <scan>1</scan> <!-- Enable Hot Deploy. --> </configuration> </plugin> </plugins> </build> </project>