Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 带自己控制器的Thymeleaf片段_Spring Mvc_Spring Boot_Thymeleaf - Fatal编程技术网

Spring mvc 带自己控制器的Thymeleaf片段

Spring mvc 带自己控制器的Thymeleaf片段,spring-mvc,spring-boot,thymeleaf,Spring Mvc,Spring Boot,Thymeleaf,我想用thymeleaf创建一个片段,它有自己的控制器,所以每当我包含片段时,就会调用控制器并填充必要的模型属性。对我来说,这听起来像是一个基本的要求,但我对thymeleaf是新手,无法理解。例如,我有一个这样的片段: <div th:fragment="table"> <tr th:each="prod : ${prods}"> <td th:text="${prod.name}"/> </tr> </div> @

我想用thymeleaf创建一个片段,它有自己的控制器,所以每当我包含片段时,就会调用控制器并填充必要的模型属性。对我来说,这听起来像是一个基本的要求,但我对thymeleaf是新手,无法理解。例如,我有一个这样的片段:

<div th:fragment="table">
  <tr th:each="prod : ${prods}">
    <td th:text="${prod.name}"/>
  </tr>
</div>
@RequestMapping(value="/getProducts")
public Model products(Model model){
    List<String> products = getProductList();
    model.addAttribute("prods", products)
    return model;
}


除了这个片段,我还有一个控制器,看起来有点像这样:

<div th:fragment="table">
  <tr th:each="prod : ${prods}">
    <td th:text="${prod.name}"/>
  </tr>
</div>
@RequestMapping(value="/getProducts")
public Model products(Model model){
    List<String> products = getProductList();
    model.addAttribute("prods", products)
    return model;
}
@RequestMapping(value=“/getProducts”)
公共模型产品(模型){
List products=getProductList();
model.addAttribute(“产品”,产品)
收益模型;
}
那我怎么才能把这两个绑起来呢?我使用的是spring boot,我没有更改或编辑任何解析器。
谢谢,Peer,von Spring MVC和模型的想法是,在视图中只渲染数据。因此,从模板中的任何位置调用服务或控制器都不是一个好主意


您可以使用函数
addDataForTableFragment(Model Model)
解决此问题。这必须从使用模板和片段的控制器调用。如果您需要许多方法中的数据,请查看a。

我手头没有参考资料,但听起来您需要发出REST调用并允许您使用结果修改DOM的Thymeleaf元素。它用于填充菜单或列表、控制可见性等。每个REST端点都是一个单独的控制器

它可以对DOM进行更实质性的更改,但是您将失去使用框架的好处,因为一切都是在服务器端完成的

这在一个关于Spring MVC和Thymeleaf的在线(Udemy?)课程中有介绍

对于将来遇到这个问题的任何人,您都会这样做,因为它允许控制器只专注于做一件事。这意味着它们更简单,如果页面被修改并且需要引入额外的数据,您不必担心更改控制器

它也更快,因为在准备响应之前不必等待所有数据可用(或等待超时)。您可以更快地响应—可能根本没有自定义数据—并在自定义数据可用时填充自定义数据


最后,不要求所有数据都来自同一个地方。如果每个微服务都提供一个REST控制器,但不对数据的使用方式做出任何假设,那么使用专门化的微服务就容易多了。

您可以使用

<th:block th:utext="${#servletContext.getRequestDispatcher('/path/to/fragment').include(#request,#response)}"/>
打电话给

<th:block th:include="~{::include(url='/path/to/fragment')}"/>