4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Spring boot でBootstrap、jQueryを使用する(WebJars)

Last updated at Posted at 2022-02-27

Spring Bootを学習中、Webjarsという便利なライブラリに触れたので、
使い方を忘れないようにアウトプットする🖋

前提条件

♦︎Spring-boot-suite:4-4.13.1

WebJarsとは

Javascriptやcssのライブラリを、Mavenで利用できるようにするライブラリのこと。

早速実装!

実装するもの

①jQuery 3.5.1
②Bootstrap 4.5.3
③WebJars-Locator

WebJars-Locatorとは??

WebJars-Locatorを使用すると、WebJarsで使用するライブラリのバージョンを意識せずコードを書けるようになる優れもの。具体的にどういうことかは後述。

①pom.xmlのdependenciesタグ内に下記を追記し、Maven インストールを実行

        <!-- jQuery -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.5.1</version>
		</dependency>
		
		<!-- bootstrap -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>bootstrap</artifactId>
			<version>4.5.3</version>
		</dependency>
		
		<!-- webjars-locator -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>webjars-locator</artifactId>
			<version>0.40</version>
		</dependency>

インストールが完了後すると、Maven依存関係内にjQuery3.5.1のjarファイルが入る。
スクリーンショット 2022-02-28 1.03.53.png

②htmlファイルにパスを追加して実装完了!!

<head>
<!-- CSS読み込み -->
<link rel="stylesheet"
	th:href="@{/webjars/bootstrap/css/bootstrap.min.css}">
<!-- JS読み込み -->
<script th:src="@{/webjars/jquery/jquery.min.js}" defer></script>
<script th:src="@{/webjars/bootstrap/js/bootstrap.min.js}" defer></script>
</head>

♦︎パスの指定にはthymeleafを使用

ここでWebJars-Locatorの出番✨

本来はMavan依存関係のフォルダ構成と同じ、3.5.1も記載しないといけないので、下記のようなパスになる。

<script th:src="@{/webjars/jquery/3.5.1/jquery.min.js}" defer>

しかしWebJars-Locatorを入れておけば、バージョン番号の分を省略する事ができ、WebJarsで使用するライブラリのバージョンを変えても、パスのコードを変更する手間が省ける。✨

※補足 deferについて

deferはHTMLの属性の一つ。
defer属性をつけると、HTMLの読み込みと Javascriptの読み込みを並行して実施してくれるので、画面表示の性能が改善される!

参考文献

♦︎WebJars 使い方メモ
https://qiita.com/opengl-8080/items/c8c5f787613c230a9827

♦︎ライブラリとは
https://wa3.i-3-i.info/word1473.html

♦︎Spring boot spring 解体新書

4
8
0

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
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?