Issue
I am learning to use thymeleaf templates for a project I am completing and seem to be missing something.
I am trying to create a very simple Hello type app, here is my code (note I am using groovy):
Controller:
@Controller
class TestController {
@RequestMapping("/")
String homePage(@RequestParam("name") String name, ModelAndView modelAndView){
modelAndView.addObject("name", name)
return "home"
}
}
home.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${name}" />
</body>
</html>
What have I missed? I just get "Hello" and nothing else when I hit:
http://localhost:8080/app-0.0.1-SNAPSHOT/?name=Sam
Solution
you have alternate option with access controller data with view name returning
@Controller
class TestController {
@RequestMapping("/")
public String homePage(@RequestParam("name") String name,Model model){
model.addAttribute("name", name)
return "home"
}
}
in your html file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${name}" />
</body>
</html>
bind model object with parameter and now you need to set addAttribute with key and value par you can access data without using ModelAndView object.
Answered By - Ravi Kavaiya
Answer Checked By - Candace Johnson (JavaFixing Volunteer)