1. 首先在pom.xml文件中添加thymeleaf和spring-boot-starter-web依赖。
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 在Controller中添加一个GetMapping方法,用于返回页面。
@GetMapping("/date")
public String date(Model model) {
   return "date";
}
  1. 在resources/templates目录下创建一个名为date.html的Thymeleaf模板文件。在文件中添加以下代码。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
   <meta charset="UTF-8">
   <title>日期选择器</title>
   <script type="text/javascript" th:src="@{/webjars/jquery/jquery.min.js}"></script>
   <script type="text/javascript" th:src="@{/webjars/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js}"></script>
   <link rel="stylesheet" th:href="@{/webjars/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css}"/>
</head>
<body>
   <div class="container">
       <h1>日期选择器</h1>
       <div class="form-group">
           <label for="date">日期:</label>
           <input type="text" class="form-control" id="date" th:name="date"/>
       </div>
   </div>
   <script type="text/javascript">
       $(document).ready(function () {
           $('#date').datepicker({
               format: 'yyyy-mm-dd',
               autoclose: true,
               todayHighlight: true,
               language: 'zh-CN',
           });
       });
   </script>
</body>
</html>
  1. 在Controller中添加一个PostMapping方法,用于接收提交的日期数据并返回。
@PostMapping("/date")
public String dateSubmit(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date, Model model) {
   model.addAttribute("date", date);
   return "date";
}
  1. 在date.html模板文件中添加一个表单,用于提交日期数据。
<form method="post" th:action="@{/date}">
   <div class="form-group">
       <label for="date">日期:</label>
       <input type="text" class="form-control" id="date" th:name="date"/>
   </div>
   <button type="submit" class="btn btn-primary">提交</button>
</form>
  1. 运行spring boot应用程序,打开浏览器并访问http://localhost:8080/date,即可看到日期选择器页面。选择一个日期并提交表单,会返回日期选择器页面并显示所选日期。

注意:此处使用了bootstrap-datepicker插件来实现日期选择器功能,需要在模板文件中添加相关的JavaScript和CSS资源引用。同时,为了能够正确地将表单数据传递给后台Controller,需要在表单元素中添加th:name属性。在后台Controller中,使用@DateTimeFormat注解将表单数据转换为Date类型

thymeleaf编写date类型时间选择器后端使用spring boot

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

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