[英]Binding between variable of html in string and a Model Class with Spring Boot
我想在html字符串的變量和Spring Boot應用程序的Model類之間創建綁定,然后我將返回一個html頁面。 這是我需要的:
@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將包含這樣的字符串:
...
<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>
...
我將發送一個這樣的json請求
{
"name":"bookowner",
"books":
[
{
"title":"title1",
"author":"author1"
},
{
"title":"title2",
"author":"author2"
}
]
}
我的模型課是這樣的
class Owner{
...
String name;
Book[] books;
...
}
class Book{
...
String title;
String author;
...
}
您向我建議什么樣的解決方案? 感謝您的幫助。
您可以使用StringTemplateResolver
的StringTemplateResolver來處理來自數據庫的模板。
例如:
@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;
}
之后,您可以在控制器中編寫如下代碼:
@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>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.