我们有 2 个配置文件:一个在我们的 Spring Boot 应用程序 (application.properties) 中,另一个在我们的 ReactJs 应用程序中(我们在 create-react-app 中使用 .env)。决定在 ReactJs 应用程序中也使用 Spring Boot application.properties。谁能指导我如何实现这一目标? 我已经阅读了“properties-reader”并尝试使用它,但是我的 ReactJs 应用程序中没有 webpack.config.js 文件。
最佳答案
Thymeleaf 提供了通过模板 (index.html) 文件将数据从 application.properties 文件传递到 Javascript 的最简单方法。
或者,它也可以使用普通的 JSP 来完成。
以下是工作示例:
选项 1:百里香
第 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>
重要提示: 确保相同的 index.html 文件存在于 Reactjs 项目的 '/public' 文件夹以及 /src/main/resources/templates/ 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
第 1 步:在 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 Controller 中使用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/
关于reactjs - 如何读取 ReactJs 应用程序中的 Spring Boot application.properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62010524/