我正在使用 thymeleaf 将变量从控制器发送到视图(HTML 文件),但它说该变量为空。
这是我的
HelloController
(src/main/java/controller/HelloController
):
@Controller
public class HelloController {
public String mensaje = "Springboot";
@GetMapping("/")
public String index(Model model){
model.addAttribute("mensaje", mensaje);
return "index";
}
}
这是 HTML 文件 (
src/main/resouces/templates/index.html
):
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1 th:text="'Hello' + ${mensaje} + '!'"></h1>
</body>
</html>
浏览器中的消息应该是“Hello Springboot!”但它说“Hellonull!”
有什么帮助吗?
尝试以下操作并告诉我。
@Controller
public class HelloController {
private String mensaje;
public HelloController() {
this.mensaje = "Springboot";
}
@GetMapping("/")
public String index(Model model){
model.addAttribute("mensaje", mensaje);
return "index";
}
}
在上面我尝试向 HelloController 类添加构造函数,这将确保变量
mensaje
正确初始化。