埋め込み Tomcat を使用して Java Web アプリケーションを作成する
最終更新日 2019年12月16日(月)
Table of Contents
このチュートリアルでは、埋め込み Tomcat を使用して単純な Java Web アプリケーションを作成する方法を示します。
各手順を実行してアプリをゼロから構築するか、最後までスキップしてこの記事用のソースを入手してください。
埋め込み Tomcat デモ のサンプルコードは GitHub で入手できます。
前提条件
- Java の基本的な知識 (インストールされている JVM および Maven のバージョンなど)
- Git の基本的な知識 (インストールされている Git のバージョンなど)
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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.heroku.sample</groupId>
<artifactId>embeddedTomcatSample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>embeddedTomcatSample Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<tomcat.version>8.5.23</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper-el</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
</dependencies>
<build>
<finalName>embeddedTomcatSample</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>appassembler-maven-plugin</artifactId>
<version>2.0.0</version>
<configuration>
<assembleDirectory>target</assembleDirectory>
<programs>
<program>
<mainClass>launch.Main</mainClass>
<name>webapp</name>
</program>
</programs>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>assemble</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
この pom.xml は、埋め込みモードで Tomcat を実行するために必要な依存関係を定義します。
最後の 3 つのエントリは、JSP ファイルを使用するアプリケーションにのみ必要です。JSP を使用しないアプリケーションにこの手法を使用する場合、最初の 3 つの依存関係をインクルードするだけでもかまいません。
1 つのプラグインも定義しています。appassembler プラグインによって生成される起動スクリプトは、クラスパスを自動的に設定し、(後で作成する) main メソッドを呼び出してアプリケーションを起動します。
ランチャークラスを追加する
Main.java
という名前のファイルを src/main/java/launch
ディレクトリに作成し、次の内容を記述します。
package launch;
import java.io.File;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
public class Main {
public static void main(String[] args) throws Exception {
String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
//The port that we should run on can be set into an environment variable
//Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if(webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
tomcat.setPort(Integer.valueOf(webPort));
StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());
// Declare an alternative location for your "WEB-INF/classes" dir
// Servlet 3.0 annotation will work
File additionWebInfClasses = new File("target/classes");
WebResourceRoot resources = new StandardRoot(ctx);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
additionWebInfClasses.getAbsolutePath(), "/"));
ctx.setResources(resources);
tomcat.start();
tomcat.getServer().await();
}
}
このコードが実行するのは、サーバーを起動するために必要な処理だけです。一時ディレクトリなどを処理する、より完全なバージョンのコードはサンプルアプリケーションに含まれています。
サーブレットを追加する
HelloServlet.java
という名前のファイルを src/main/java/servlet
ディレクトリに作成し、次の内容を記述します。
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(
name = "MyServlet",
urlPatterns = {"/hello"}
)
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletOutputStream out = resp.getOutputStream();
out.write("hello heroku".getBytes());
out.flush();
out.close();
}
}
これは、アノテーションを使用して自らを設定する単純なサーブレットです。
JSP を追加する
index.jsp
という名前のファイルを src/main/webapp
ディレクトリに作成します。
<html>
<body>
<h2>Hello Heroku!</h2>
</body>
</html>
アプリケーションを実行する
開始スクリプトを生成するには、次のように実行します。
$ mvn package
次に、スクリプトを実行します。Mac および Linux では、コマンドは次のとおりです。
$ sh target/bin/webapp
Windows では、コマンドは次のとおりです。
C:/> target/bin/webapp.bat
これで、アプリケーションがポート 8080 で起動するようになります。JSP は http://localhost:8080 で、サーブレットは http://localhost:8080/hello でそれぞれ確認できます。
Heroku へのアプリケーションのデプロイ
Procfile の作成
プロジェクトルートの Procfile
で、アプリケーションを実行する方法を宣言します。次の 1 行の内容で、このファイルを作成します。
web: sh target/bin/webapp
Procfile の詳細も確認してください。
Heroku にデプロイする
Heroku へのデプロイは、Heroku Maven プラグインまたは Git を使用して実行できます。後者については、この記事で説明します。
変更を Git にコミットします。
$ git init
$ git add .
$ git commit -m "Ready to deploy"
アプリを作成します。
$ heroku create
Creating high-lightning-129... done, stack is heroku-18
http://high-lightning-129.herokuapp.com/ | git@heroku.com:high-lightning-129.git
Git remote heroku added
コードをデプロイします。
$ git push heroku master
Counting objects: 227, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (117/117), done.
Writing objects: 100% (227/227), 101.06 KiB, done.
Total 227 (delta 99), reused 220 (delta 98)
-----> Heroku receiving push
-----> Java app detected
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 36.612s
[INFO] Finished at: Tue Aug 30 04:03:02 UTC 2011
[INFO] Final Memory: 19M/287M
[INFO] ------------------------------------------------------------------------
-----> Discovering process types
Procfile declares types -> web
-----> Compiled slug size is 62.7MB
-----> Launching... done, v5
http://pure-window-800.herokuapp.com deployed to Heroku
これで完了です。Web アプリが Heroku で稼働するようになりました。次のようにしてブラウザで開きます。
$ heroku open
JSP が表示され、/hello に移動してサーブレットを確認できます。
ソースを複製する
作成手順をスキップする場合、次のようにして、完成したサンプルを複製できます。
$ git clone https://github.com/heroku/devcenter-embedded-tomcat