I want to create a binding between variables of html string and a Model Class for a spring boot app and then i will return a html page. Here what I need:
@PostMapping(path = {"/hashmap"})
public String GetHtmlPage(@RequestBody Owner owner) {
String htmlPage=contractsRepository.getById(1);
//i need a solution like "binding" method.
//but i don't know which library i can use and
//how can i do this implementation
String htmlPageAfterBinding=binding(htmlPage,owner);
return htmlPageAfterBinding;
}
htmlPage will include a string like this:
...
<p th:text="'Hello, ' + ${name} + '!'" />
<tr th:each="book : ${books}">
<td><span th:text="${book.title}"> Title </span></td>
<td><span th:text="${book.author}"> Author </span></td>
</tr>
...
and i will send a json request like this
{
"name":"bookowner",
"books":
[
{
"title":"title1",
"author":"author1"
},
{
"title":"title2",
"author":"author2"
}
]
}
my model classes like these
class Owner{
...
String name;
Book[] books;
...
}
class Book{
...
String title;
String author;
...
}
What kind of a solution do you suggest to me? Thanks for your helps.
You can use the StringTemplateResolver
of Thymeleaf to handle templates that are coming from a database.
For example:
@Bean
public TemplateEngine stringTemplateEngine(StringTemplateResolver resolver) {
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
return templateEngine;
}
@Bean
public StringTemplateResolver stringTemplateResolver() {
StringTemplateResolver resolver = new StringTemplateResolver();
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
After that, you can write something like this within your controllers:
@GetMapping("/")
public String getResult(ModelMap modelMap) {
Owner owner = new Owner("bookowner", Arrays.asList(
new Book("title1", "author1"),
new Book("title2", "author2")
));
modelMap.addAttribute("owner", owner);
return
"<p th:text=\"'Hello, ' + ${owner.name} + '!'\" />" +
"<table>" +
"<tr><th>Title</th><th>Author</th></tr>" +
"<tr th:each=\"book : ${owner.books}\">" +
"<td><span th:text=\"${book.title}\">Title</span></td>" +
"<td><span th:text=\"${book.author}\">Author</span></td>" +
"</tr>" +
"</table>";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.