首页 > 解决方案 > 为什么 th:field 在 Spring View 中不起作用

问题描述

我正在尝试创建一个 HTML Web 表单来创建赞助事件(一个模型类),我有一个 Spring 控制器、一个 Thymeleaf 视图和实体模型。但是,无论我尝试什么,我似乎都无法让 th:field 工作。

我正在使用此页面作为参考https://spring.io/guides/gs/handling-form-submission/

看法

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
  <head>
    <title>Create a Sponsored Event</title>
  </head>
  <body>
    <h1>Create a Sponsored Event</h1>
    <form action="#" th:action="@{/event/create/submit}" th:object="${sponsor}" method="post">
      <input type="text" th:field="*{id}"/> <!-- This Line -->
    </form>
  </body>
</html>

控制器

@Controller
@RequestMapping("events")
public class SponsorController {

  private static final String CREATE_PAGE = "events/create";

  @GetMapping("/create")
  public String addSponsorEvent(Model model) {
    model.addAttribute("sponsor", new Sponsor());

    return CREATE_PAGE;
  }
}

模型

@Data
@Entity
@NoArgsConstructor
@Accessors(fluent = true)
@Table(name = "sponsor_form")
public class Sponsor {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;

}

我也试过改变这个

<input type="text" th:field="*{id}"/>
<input type="text" th:field="*{id()}"/>
<input type="text" th:field="*{sponsor.id}"/>
<input type="text" th:field="*{sponsor.id()}"/>

我得到了错误:

原因:org.attoparser.ParseException:执行处理器“org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor”时出错(模板:“events/create” - 第 9 行,第 26 列)

标签: javaspringthymeleaf

解决方案


在 Model 类 Sponsors 中,错误是由 @Accessors(fluent = true) 引起的,我删除了这一行并解决了这个问题。


推荐阅读