I am using thymeleaf to send variables from the controller to the view (HTML file) but it says that is null.
This is my 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";
}
}
This is the HTML file (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>
The message in the browser should be "Hello Springboot!" but it says "Hellonull!"
Any help?
try the below and let me know.
@Controller
public class HelloController {
private String mensaje;
public HelloController() {
this.mensaje = "Springboot";
}
@GetMapping("/")
public String index(Model model){
model.addAttribute("mensaje", mensaje);
return "index";
}
}
in the above i tried by adding constructor to the HelloController class , that will make sure that variable mensaje
is initialized correctly.