首页 > 解决方案 > Thymeleaf th:字段未向控制器提交任何值

问题描述

嘿嘿,

我对 Thymeleaf 有一点问题,尽管我咨询了很多类似的问题,但我没有找到问题。

我是 Spring 新手,基本上我想做的就是通过表单提交一些数据,然后将其保存在数据库中。这是我的控制器

    @RequestMapping(value = "user", method = RequestMethod.GET)
    public String showAllCustomers(Model model) {

        model.addAttribute("customer", new Customer());
        return "DisplayCustomerAll";
    }

    @PostMapping("/create")
    public String saveStudent(@ModelAttribute Customer customer) {
        Repository.save(customer);
        return "DisplayCustomerAll";
    }

我的实体如下所示:

   @Entity
   public class Customer {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        private String firstName;
    
        private String lastName;
    
    
        public Long getId() {
            return id;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public void setFirstName(String firstName) {
            firstName = firstName;
        }
    
        public void setLastName(String lastName) {
            lastName = lastName;
        }
    }

和html如下:

    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org" lang="en">
    <head>
      <title>Title</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    <header th:insert="fragments/navbar.html :: navbar"> </header>
    <table>
      <thead>
      <tr>
        <th> First Name </th>
        <th> Last Name </th>
      </tr>
      </thead>
      <tbody>
      <tr th:each="customer1 : ${customers}">
        <td><span th:text="${customer1.firstName}"> Title </span></td>
        <td><span th:text="${customer1.lastName}"> Author </span></td>
      </tr>
      </tbody>
    </table>
    <form th:action="@{/create}" th:object="${customer}" method="post">
        <input type="hidden" th:field="*{id}">
        <input type="text" th:field="*{firstName}" >
        <input type="text" th:field="*{lastName}" >
      <input type="submit" value="Create User">
    </form>
    
    <p th:text="${customer.firstName}" > </p>
    <p th:text="${customer.getFirstName()}" > </p>
    
    </body>
    </html>

我浏览了很多指南并尝试了很多,但有些客户总是保持空白。如果有人可以提供帮助,我将不胜感激

标签: spring

解决方案


推荐阅读