使用Spring + Hibernate创建HTML表单

时间:2017-10-13 11:52:13

标签: spring thymeleaf

我有3个班级:

First class是一个存储String变量的实体:

@Entity
@Table(name = "mods_langs_texts", catalog = "artfunpw")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class ModsLangsTexts implements java.io.Serializable {


    @Column(name = "Title", nullable = false, length = 300)
    public String getTitle() {
        return this.title;
    }

第二个实体是关系:

@Entity
@Table(name = "mods_langs_texts_relations", catalog = "artfunpw")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class ModsLangsTextsRelations implements java.io.Serializable {

   @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "textId", nullable = false)
    public ModsLangsTexts getModsLangsTexts() {
        return this.modLangsTexts;
    }

第三个实体是主要类:

@Entity
@Table(name = "mods", catalog = "artfunpw")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class Mod implements java.io.Serializable {

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "mod")
    @Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
    public Set<ModsLangsTextsRelations> getModsLangsTextsRelationses() {
        return this.modsLangsTextsRelationses;
    }

我正在尝试使用代码创建HTML表单:

m.addAttribute("formClass", mod);

和HTML代码:

<p th:text="${formClass.modsLangsTextsRelationses.toArray()[0].getModsLangsTexts().title}" />

                <form action="" th:object='${formClass}' method="POST">

                    <input type="hidden" th:field='*{id}' />

                    Title: <input type="text" th:field='${formClass.modsLangsTextsRelationses.toArray()[0].getModsLangsTexts().title}' />
                    <br />

但它失败了,错误:

2017-10-13 14:33:56.661 ERROR 4744 --- [nio-8080-exec-9] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-9] Exception processing template "mods/editPages/editModPage": Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (mods/editPages/editModPage:57)

第57行是带代码的行:

Title: <input type="text" th:field='${formClass.modsLangsTextsRelationses.toArray()[0].getModsLangsTexts().title}' />

同时代码

<p th:text="${formClass.modsLangsTextsRelationses.toArray()[0].getModsLangsTexts().title}" />

工作正常。

如何使用Spring + Hibernate + Thymeleaf从HTML表单代码访问内部对象?

1 个答案:

答案 0 :(得分:0)

查看thymeleaf tutorial

由于th:field属性

form是您在th:object代码上声明的命令对象的字段引用

从教程:

<form action="#" th:action="@{/seedstartermng}" th:object="${seedStarter}" method="post">
    <input type="text" th:field="*{datePlanted}" />
</form>

根据您的情况改编:

<form action="#" th:action="@{???}" th:object="${formClass.modsLangsTextsRelationses.toArray()[0].getModsLangsTexts()}" method="post">
     <input type="text" th:field="*{title}" />
</form>

我怀疑它会以这种方式运作。看看section 7.6 : dynamic fields