Spring Boot | WebJarsを使用する

WebJarsとは?

WebJarsは、jQueryやBootstrapなどのクライアントサイドライブラリをJARファイルとしてパッケージ化し、Javaライブラリと同じようにMavenやGradleで管理できるようにするサービスです。

WebJars - Web Libraries in Jars

jQuery UIを追加する

コードの作成

build.gradle

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
+   compile 'org.webjars:jquery-ui:1.11.4'
}

src/main/resources/static/index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>jQuery UI by WebJars</title>

    <link rel="stylesheet" href="/webjars/jquery-ui/1.11.4/jquery-ui.min.css" />

    <script src="/webjars/jquery/1.11.1/jquery.min.js"></script>
    <script src="/webjars/jquery-ui/1.11.4/jquery-ui.min.js"></script>
    <script>
    $(function() {
        $('button')
          .button()
          .on('click', function() {
              alert('Hello WebJars!!');
          });
    });
    </script>
  </head>
  <body>
    <button>Hello</button>
  </body>
</html>

実行結果

サーバーを起動し、ブラウザーでhttp://localhost:8080/を開きます。

説明

  • WebJarsで追加したライブラリは、webjars/以下のパスからアクセスできます。
  • JARファイル内のフォルダー構成を確認するか、WebJarsでFilesリンクをクリックすると確認できます。