thymelaf表单中的数据未正确保存到数据库中

时间:2019-05-07 10:07:53

标签: forms spring-mvc spring-data-jpa thymeleaf

我正在处理将实体从thymealaf形式保存到数据库的问题。


我目前的做法。

register.html中的胸腺形式

 <form action="save" th:method="post" th:action="@{save}" th:object="${customer}">
            <input type ="text" th:field="*{firstName}" placeholder="First Name" /><br />
            <input type ="text" th:field="*{lastName}" placeholder="Last Name" /><br />
            <input type="email" th:field="*{emailAddress}"  placeholder="Email" /><br />
            <input type="password" th:field="*{password}"  placeholder="Password" /><br />
            <input style="text-align: center" type="submit" value="Register" /> </form>

控制器方法:

@RequestMapping("/home")
  public String home(Model model){
    model.addAttribute("customer", new Customer());
    return "register";
  }

  @RequestMapping("save")
  public String save(@ModelAttribute(value = "customer") Customer customer) {
    customerRepository.save(customer);
    return "saved";
  }

如所附的屏幕截图所示,数据绑定存在问题

database results

2 个答案:

答案 0 :(得分:0)

问题解决了。只需更改以下项的依赖关系:

        <dependency>
           <groupId>org.thymeleaf</groupId>
          <artifactId>thymeleaf-spring5</artifactId>
           <version>3.0.9.RELEASE</version>
       </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>

答案 1 :(得分:0)

如我所见,您没有在输入字段中提及名称 thymelaf 使用名称绑定数据 所以你必须在输入字段中添加一个名称,如下

<form action="save" th:method="post" action="save" th:object="${customer}">
            <input type ="text" name="first_name"  placeholder="First Name"  /><br />
            <input type ="text" name="last_name" placeholder="Last Name" /><br />
            <input type="email" name="email_address"  placeholder="Email" /><br />
            <input type="password" name="password"  placeholder="Password" /><br />
            <input style="text-align: center" type="submit" value="Register" /> </form>

注意:-输入字段中的名称应与表格中的名称匹配

相关问题