【问题标题】:(Spring, Thymeleaf) How to request to controller 'POST' with list of model inside a model?(Spring,Thymeleaf)如何使用模型内的模型列表向控制器“POST”请求?
【发布时间】:2017-11-02 00:24:15
【问题描述】:

问题

我尝试了以下来源。但发生错误“对象验证失败”。
此链接引用(http://bitbybitblog.com/forms-and-data-models-in-spring-mvc/)。
我猜如何将数据(输入值)发送到模型“Shop”的控制器而不会出现任何错误。
我认为无与伦比的模型“商店”和 HTML 表单数据。无法找出解决方案。
如何修复“标签”输入名称?

来源

公共类标签 { 私人长ID; 私有字符串名称; 私人日期 regDate = new Date(); } 公共类商店 { 私人长ID; 私有字符串名称; 私人字符串网址; 私有字符串特征图像路径; 私有列表&ltTag&gt tag = new ArrayList&lt&gt(); 私人 ShopStatus 状态 = ShopStatus.SHOW; 私人日期 expireDate; 私人日期更新日期; 私人日期 regDate; } 控制器
@RequestMapping(value = "/edit/update", method = RequestMethod.POST) 公共字符串更新(@ModelAttribute Shop shop){ if (shop.getId() == null) { shopService.createShop(shop); } 返回“重定向:/”; } HTML/Thymeleaf
&ltform name="editor" method="post" action="/edit/update"&gt &lt字段集&gt &ltinput name='name' th:value='${data.name}'/&gt &ltinput name='tag[0].id'/&gt&ltinput name='tag[0].name'/&gt &lt/字段集&gt &lt/形式&gt


结果

出现这个问题然后在浏览器上提交表单“编辑器”。

此应用程序没有 /error 的显式映射,因此您将其视为后备。
出现意外错误(类型=错误请求,状态=400)。 对象='shop' 的验证失败。错误计数:1

【问题讨论】:

  • 那篇关于 jsp spring 的博客文章,但是您尝试了 thymeleaf 而不是 jsp。您需要检查 thymleaf 文档。我可以看到这里缺少一些东西。表单没有 th:object 并且表单对象属性需要使用 th:field 绑定。文档在这里thymeleaf.org/doc/tutorials/2.1/…
  • @SAP 感谢您的回复。请参考这个 thymeleaf 版本是 3.x。我已经尝试多次添加“th:object”属性并检查了文档。没有'th:object'的其他页面不会发生。
  • 您没有关注 Thymeleaf 文档。检查这个:thymeleaf.org/doc/tutorials/2.1/…。您没有在输入字段中包含任何属性,例如“th:field”,这些属性用于将您的字段与控制器中的 ModelAttribute 映射
  • @Afridi 我明白了。但不确定。我发现了确切的问题。谢谢你的回复

标签: html spring post spring-boot thymeleaf


【解决方案1】:

我的来源没有问题。发生在另一边。
实际上 HTML 端有 'expireDate' 输入。但发送到输入的控制器 NULL 值(模型 'Shop' 没有定义默认值)。
是我的错。

此外,如果跟随控制器源代码,我们可以使用不带'th:object'的“FORM”


控制器

@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String edit(Model model) {
    model.addAttribute("data", new Shop());
    return "shop/edit";
}

@RequestMapping(value = "/edit/update", method = RequestMethod.POST)
public String update(@ModelAttribute Shop shop) {
    if (shop.getId() == null) {
        shopService.createShop(shop);
    }

    return "redirect:/";
}

【讨论】:

  • 当然,如果您将 new Shop() 对象放入模型,则可以不使用 th:object。但是,您还没有将标签添加到标签数组列表中。
猜你喜欢
  • 2021-11-21
  • 1970-01-01
  • 2021-04-08
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2017-02-02
  • 1970-01-01
相关资源
最近更新 更多