Thymeleaf 提供了通过模板 (index.html) 文件将数据从 application.properties 文件传递到 Javascript 的最简单方法。
或者,也可以使用普通的JSP来完成。
以下是工作示例:
选项 1:百里香叶
第一步:将感兴趣的数据属性定义为index.html文件中的隐藏元素
<div id="root"></div> ---> Div to be updated by react
....
<span id="myData" hidden></span>
<!-- Script to set variables through Thymeleaf -->
<script th:inline="javascript">
var myData = "[${myData}]]";
document.getElementById("myData").innerHTML = myData;
</script>
重要提示:
确保 Reactjs 项目的 '/public' 文件夹以及 /src/main/resources/templates 中存在相同的 index.html 文件/ spring boot 项目的文件夹。
第二步:使用Spring Boot中的model.addAttribute()方法调用Thymeleaf设置index.html文件中的数据
@GetMapping("/")
public String index(Model model) {
// Get the value of my.data from application.properties file
@Value("${my.data}")
private String myData;
// Call Thymeleaf to set the data value in the .html file
model.addAttribute("myData", myData);
return "index";
}
第 3 步:更新 ReactJS 代码以使用 document.getElementById 读取有趣的属性
let myData = document.getElementById("myData").innerHTML
更多信息:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
https://attacomsian.com/blog/thymeleaf-set-javascript-variable
选项 2:JSP
第一步:将感兴趣的数据属性定义为index.jsp文件中的隐藏元素
index.jsp 的位置: src/main/webapp/WEB-INF/jsp/index.jsp
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<!-- Head section here -->
</head>
<body>
<!-- Div to be updated by react -->
<div id="root">
</div>
<!-- Include the interesting attribute as a hidden field -->
<span id="myData" hidden>${myData}</span>
</body>
</html>
重要提示:
确保reactjs项目的/public/index.html文件与src/main/webapp/WEB-INF/的内容相同(<body>...</body>) jsp/index.jsp spring boot项目文件)
第二步:在Spring Boot控制器中使用map.put()更新JSP中的数据
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomePageController{
// Read data from application.properties
@Value("${my.data}")
private String myData;
// Update data attributes of JSP using map.put
@GetMapping("/")
public String index( Map<String, Object> map ) {
map.put("myData", myData);
return "index";
}
}
第 3 步:更新 ReactJS 代码以使用 document.getElementById 读取有趣的属性
let myData = document.getElementById("myData").innerHTML
更多信息:
https://mkyong.com/spring-boot/spring-boot-hello-world-example-jsp/