【问题标题】:Thymeleaf: use the same template with dynamic url from different controllersThymeleaf:使用来自不同控制器的动态 url 相同的模板
【发布时间】:2017-10-07 14:15:25
【问题描述】:

我有两个执行相同功能的 html 模板,但由两个不同的控制器处理:

主持人控制器处理的第一个 html

<form th:action="@{/moderator/new-user-form}" th:object="${caltest}" method="post"
     enctype="multipart/form-data" class="form-validate form row">
    <!-- some code -->
</form>

管理控制器处理的第二个 html

<form th:action="@{/admin/new-user-form}" th:object="${caltest}" method="post"
     enctype="multipart/form-data" class="form-validate form row">
    <!-- some code -->
</form>

如您所见,这些模板仅在action url 上有所不同:

th:action="@{/someurl}"

是否可以将同一模板与来自不同控制器的动态 url 一起使用?

【问题讨论】:

  • 我问这个问题是为了避免多次重复相同的代码
  • 你从哪里得到标识符来调用正确的控制器?在你的情况下adminmoderator?或者至少是完整的网址?
  • 你试过了吗?你有没有得到任何错误?不同的控制器可以返回相同的模板,只要它们映射到不同的 URL 路径
  • @SAP 是的,我现在正在使用它,没有任何错误。我的网址不同,因为每个控制器都相应地映射(例如:/admin/save-user-form、/moderator/save-user-form)
  • @Patrick 这就是我在项目中获取 url 的确切方式:@Controller @RequestMapping(value = "/admin") @PropertySource("classpath:application.properties") public class AdminController { //some other code @RequestMapping("/submit-murojaat") public String newMurojat(Model model) { model.addAttribute("caltest", new Caltest()); model.addAttribute("action", "/save-new-murojaat"); return "murojaatNewS"; } }

标签: java html spring-boot controller thymeleaf


【解决方案1】:

有很多不同的方法可以做到这一点...最简单的方法是在控制器中使用相同的模板,并在每个控制器中传递一个包含正确操作的变量。

例如:

// Moderator controller
@RequestMapping(value = "/moderator")
public String moderator(Map<String, Object> model) {
  model.put("action", "/moderator/new-user-form");
  return "new-user-form";
}

// Admin controller
@RequestMapping(value = "/moderator")
public String moderator(Map<String, Object> model) {
  model.put("action", "/admin/new-user-form");
  return "new-user-form";
}

在html中

<form th:action="@{${action}}">

如果这不合适,您可以将表单本身转换为片段,然后将操作作为参数传递。像这样的:

<!-- Fragment -->
<form th:fragment="userform (action)" th:action="@{${action}}">
  .
  .
  .
</form>

<!-- Including the fragment -->
<div th:replace="fragments/userform :: userform(action='/admin/new-user-form')" />
<!-- or -->
<div th:replace="fragments/userform :: userform(action='/moderator/new-user-form')" />

【讨论】:

  • 这非常有效! &lt;form th:action="@{${action}}"&gt;非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 2021-01-28
相关资源
最近更新 更多