SpringBoot2.6にJavaScriptとCSSファイルを使用する
環境
Windows10 64bit
Spring Boot 2.6.3
Spring Tool Suite 4
JDK 11
thymeleaf 3
書式
th:href="@{cssファイル}"
th:src="@{jsファイル}"
使用例
1.CSSファイルの定義(src/main/resources/static/css/cft.css)
@charset "UTF-8";
#tt{
color:red;
font-size:14px;
font-weight:bold;
}
@charset "UTF-8";
#tt{
color:red;
font-size:14px;
font-weight:bold;
}
@charset "UTF-8"; #tt{ color:red; font-size:14px; font-weight:bold; }
2.JavaScriptファイルの定義(src/main/resources/static/js/cft.js)
const cft = document.getElementById("tt");
var style = cft.style;
cft.textContent = "thymeleafでjsを使用するサンプル";
style.backgroundColor = 'skyblue';
const cft = document.getElementById("tt");
var style = cft.style;
cft.textContent = "thymeleafでjsを使用するサンプル";
style.backgroundColor = 'skyblue';
const cft = document.getElementById("tt"); var style = cft.style; cft.textContent = "thymeleafでjsを使用するサンプル"; style.backgroundColor = 'skyblue';
3.cssとjavascriptを使用するhtmlファイル(src/main/resources/templates/ctn/index.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>Spring thymeleafテストページ</title>
<link th:href="@{/css/cft.css}" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="tt">thymeleafでcssとjsファイルを使用して画面を表示するサンプル</div>
<script th:src="@{/js/cft.js}"></script>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>Spring thymeleafテストページ</title>
<link th:href="@{/css/cft.css}" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="tt">thymeleafでcssとjsファイルを使用して画面を表示するサンプル</div>
<script th:src="@{/js/cft.js}"></script>
</body>
</html>
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8" /> <title>Spring thymeleafテストページ</title> <link th:href="@{/css/cft.css}" rel="stylesheet" type="text/css"/> </head> <body> <div id="tt">thymeleafでcssとjsファイルを使用して画面を表示するサンプル</div> <script th:src="@{/js/cft.js}"></script> </body> </html>
4.コントローラのクラス(JsCssController.java)
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class JsCssController {
//パス「ctn」にアクセス
@GetMapping("/ctn")
public String funA() {
//ctnフォルダ配下index.htmlを呼び出す
return "ctn/index";
}
}
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class JsCssController {
//パス「ctn」にアクセス
@GetMapping("/ctn")
public String funA() {
//ctnフォルダ配下index.htmlを呼び出す
return "ctn/index";
}
}
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class JsCssController { //パス「ctn」にアクセス @GetMapping("/ctn") public String funA() { //ctnフォルダ配下index.htmlを呼び出す return "ctn/index"; } }
5.動作確認
http://127.0.0.1:8080/ctn
divのセレクタID「tt」にCSSとjavaScriptの内容が表示されます。