サーブレットで面倒なのはTomcatとの付き合いです。
Spring BootでSpring Webを使うと組み込みTomcatが動くので、Tomcatのことを気にしなくてよくなりますね。
そこでサーブレット動かすと勉強しやすいんでは、と思ったので試してみます。
まず、spring initializrでSpring Webを追加したプロジェクトを作ります。
https://start.spring.io/
このリンクから、設定済みのspring initializrを開けます。Mavenにしているので、Gradleがいい人は選択しなおしてください。
https://start.spring.io/#!type=maven-project&language=java&platformVersion=3.1.1&packaging=jar&jvmVersion=17&groupId=com.example&artifactId=demo&name=ServletDemo&description=Servlet%20Demo%20project%20for%20Spring%20Boot&packageName=com.example.servletdemo&dependencies=web
[GENERATE]ボタンを押してダウンロードしたzipを解凍します。こんな感じになっているはず。
アプリケーションクラスに @ServletComponentScan
を付けます。
package com.example.servletdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class ServletDemoApplication { public static void main(String[] args) { SpringApplication.run(ServletDemoApplication.class, args); } }
そしてサーブレットクラスを定義します。
サーブレットのパッケージがjakartaになってるのは感慨深さ。
package com.example.servletdemo; 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(urlPatterns = "/hello") public class SampleServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println(""" <h1>Hello Servlet</h1> Hello! """); } }
アプリケーションクラスを実行させると、Spring Bootが起動します。
http://localhost:8080/hello
にアクセスすると・・・
できました!
これでいいのでは。オートリロードなども使えると思うので、かなり楽ができそう。
ただし、JSPを動かそうとすると結構めんどいので、それなら最初からJakartaEEを使うほうがいいかも。これもアプリサーバーのインストールや起動、デプロイなどをやらなくていいようになっています。
起動やアクセスポートはランタイムごとに違うので、ダウンロード時についてくるreadmeを確認する必要があります。
https://start.jakarta.ee/