将数据从html发送到Thymeleaf的控制器?

use*_*758 9 spring spring-mvc thymeleaf

我必须从html页面(带有少量输入文本字段的简单表单)向页面控制器发送数据,然后发送到数据库.我正在使用thymeleaf 2.0.17,spring 3.0.我搜索并检查了一些解决方案,但没有奏效.也许有人有同样的问题,并找到一些好的解决方案.请帮忙.谢谢

Shi*_*Kai 43

您可以在http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#creating-a-form中找到一个示例 .

正如教程所示,您需要使用th:object,th:actionth:field在Thymeleaf中创建表单.

它看起来像这样:

控制器:

@RequestMapping(value = "/showForm", method=RequestMethod.GET)
public String showForm(Model model) {
  Foo foo = new Foo();
  foo.setBar("bar");

  model.addAttribute("foo", foo);
  ...
}

@RequestMapping(value = "/processForm", method=RequestMethod.POST)
public String processForm(@ModelAttribute(value="foo") Foo foo) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<form action="#" th:action="@{/processForm}" th:object="${foo}" method="post">
  <input type="text" th:field="*{bar}" />
  <input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

Foo.java:

public class Foo {
  private String bar;

  public String getBar() {
    return bar;
  }

  public void setBar(String bar) {
    this.bar = bar;
  }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 对我不起作用.我收到以下错误:``执行处理器时出错'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor'(模板:"fragments/send" - 第21行,第55行)``当我使用``th:字段时我的表格上有``标签. (5认同)