如何使用thymaleaf将碎片的动态数据获取到另一个页面



我想将信息(动态生成(从一个html页面获取到另一个html页。

我在第一个html页面中使用了一个标记th:frage,在第二个html页面使用了th:replace。

但我只得到第一页的静态内容,有可能得到动态数据吗?有人能帮我吗。

提前谢谢。

这是我的Java代码:

@Controller
public class WelcomeController {
@RequestMapping("/")
public ModelAndView usingToList(Model model) {
List<String> colors = new ArrayList<>();
colors.add("green");
colors.add("yellow");
colors.add("red");
colors.add("blue");
model.addAttribute("message", "harika");
model.addAttribute("colors", colors);

List<String> colors2 = new ArrayList<>();
colors2.add("pinkish");
colors2.add("green");
colors2.add("yellow");
colors2.add("red");
colors2.add("blue");
model.addAttribute("coloring", colors2);
ModelAndView mv = new ModelAndView();   
mv.setViewName("welcome");
return mv;

}



@GetMapping("/toList")
public String usingToList2(Model model,String color) {
System.out.println("inside uselist");
List<String> colors2 = new ArrayList<>();
if(color.equals("pinkish"))
{
colors2.add("pinkish");
colors2.add("amity");
colors2.add("pimity");
}
if(color.equals("green"))
{
colors2.add("greenish");
colors2.add("amity");
colors2.add("Pretty");
}

model.addAttribute("colors", colors2);

return "welcome";
}
}

以下是我的示例POC:

这是我的片段:nav.html,它动态加载颜色。我在所有页面中都使用这个边栏片段。当我转到另一页时,侧栏中的数据会消失。

<div th:fragment="sidebar2">
<div class="sidebar-sticky pt-3">
<ul class="nav flex-column" id="accordionSidebar">
<li class="nav-item">
<a type="button"
id="collapse"
data-toggle="collapse"
data-target="#collapseExample"
aria-expanded="false" aria-
controls="collapseExample">
<span class="menu-title">Colors List</span>
<span data-feather="plus-circle"></span>
</a>
<div class="collapse" id="collapseExample">
<ul class="nav flex-column sub-menu"
id="collapseExample2">
<li th:each="color : 
${coloring}">
<a th:href="@{/toList(color=${color})}"
th:text="${color}"> ></a>
</li>
</ul>
</div>
</div>

welcome.html:

<div th:replace="fragments/nav :: sidebar2"></div>
<main role="main" class="container">
<div class="starter-template">
<h1>Spring Boot Web Thymeleaf Example</h1>
<h2>
<span th:text="'Hello, ' + ${message}"></span>
</h2>
</div>
<ol>
<li th:each="color2 : ${colors}" th:text="${color2}"></li>
</ol>
</main>

当您从一个页面导航到另一个页面时,Model再次为空(除非您正在执行<form>POST(。

当您通过usingToList2()显示welcome.html胸腺素模板时,则Model中没有coloring密钥。

要解决此问题,还可以在usingToList2()控制器方法中添加coloring密钥。

更新:如果所有控制器都需要,您可以使用@ControllerAdvice:

@ControllerAdvice
public class GlobalControllerAdvice {

@ModelAttribute("coloring")
public List<String> coloring() {
List<String> colors2 = new ArrayList<>();
colors2.add("pinkish");
colors2.add("green");
colors2.add("yellow");
colors2.add("red");
colors2.add("blue");
}
}

或者,如果一个控制器中的所有方法都需要它,您可以将该方法添加到控制器类本身中。

相关内容

最新更新