1. pom.xml 文件中添加 Thymeleaf、Spring Boot Starter Thymeleaf、Spring Boot Starter Data JPA 和 MySQL Connector Java 的依赖。
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
  1. application.properties 中配置数据库连接信息。
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
  1. 创建实体类。
@Entity
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  
  private String name;
  
  @Temporal(TemporalType.DATE)
  private Date birthdate;
  
  // getters and setters
}

注意:使用 @Temporal 注解将 Date 类型映射为数据库中的日期类型。

  1. 创建 Repository。
public interface UserRepository extends JpaRepository<User, Long> {
}
  1. 创建 Controller。
@Controller
public class UserController {
  @Autowired
  private UserRepository userRepository;
  
  @GetMapping("/")
  public String index(Model model) {
    model.addAttribute("user", new User());
    return "index";
  }
  
  @PostMapping("/save")
  public String save(@ModelAttribute("user") User user) {
    userRepository.save(user);
    return "redirect:/";
  }
}
  1. 创建 HTML 页面。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>User Form</title>
</head>
<body>
  <h1>User Form</h1>
  <form th:action="@{/save}" th:object="${user}" method="post">
    <label>Name:</label>
    <input type="text" th:field="*{name}" />
    <br />
    <label>Birthdate:</label>
    <input type="date" th:field="*{birthdate}" />
    <br />
    <input type="submit" value="Save" />
  </form>
</body>
</html>

注意:使用 th:field 将表单字段与实体类属性绑定,使用 th:action 指定表单提交的 URL。

  1. 运行程序,访问 http://localhost:8080/,即可看到表单页面。填写表单并提交后,数据将保存到数据库中。
Spring Boot 使用 Thymeleaf 和 JPA 创建日期选择器表单

原文地址: https://www.cveoy.top/t/topic/nsR0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录