LoginSignup
8
2
はじめての記事投稿
Qiita Engineer Festa20242024年7月17日まで開催中!

【Spring Boot + Thymeleaf】外部CSS読み込みに苦戦した話

Last updated at Posted at 2024-06-25

背景

今年から新卒エンジニアになり、研修でSpring Boot+Thymeleafを用いてWebアプリケーションを作成していました。HTML上に記述していたstyleコードが長くなったので外部CSSを作成して読み込もうとしたところうまく表示できなかったので、解決までの一部始終を書きたいと思います。

動作環境

  • Windows11
  • Eclipse 4.30.0
  • Spring Boot 3.3.0
  • Thymeleaf 3.1.0

ファイル構成

/src/main/resources
    ├ db.migration
    ├ templates
        ├ common
            └ head.html
        ├ style
            └ style.css
        ├ user
            ├ detail.html
            ├ list.html
        └ index.html
    ├ static
        ︙

状況

上のファイル構成でstyle.cssにスタイルを記述し、HTMLには

<link th:href="@{style/style.css}" rel="stylesheet">

の一文をheadに加えましたが、スタイルが適用されませんでした。

原因と解決法

公式ドキュメント(正しくは公式ドキュメントを和訳していただいているもの)によると、Spring BootではJavaScript、CSS などの静的リソースは src/main/resources/staticに配置する必要があるようです。また自分のHTMLではリンクの指定の仕方も間違っていました。正しいファイル構成は以下のようになります。

/src/main/resources
    ├ db.migration
    ├ templates
        ├ common
            └ head.html
        ├ user
            ├ detail.html
            ├ list.html
        └ index.html
    ├ static
        └ style
            └ style.css
        ︙

また、HTMLコードを以下のように変更すると、

<link th:href="@{/style/style.css}" rel="stylesheet">

無事にCSSに記述したスタイルが適用されたページを表示することができました!
同じような事象でつまづいている人の一助になれば幸いです。

8
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
2