<h2>Spring Boot Thymeleaf 日期选择器实现</h2>
<p>本教程将引导您使用 Thymeleaf 和 Spring Boot 创建一个简单的日期选择器功能。</p>
<h3>1. 添加依赖</h3>
<p>首先,在您的 <code>pom.xml</code> 文件中添加 Thymeleaf 和 Spring Boot Starter Web 依赖:xml<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></p>
<h3>2. 创建 Controller</h3>
<p>在您的 Controller 类中添加一个 <code>GetMapping</code> 方法,用于返回日期选择器页面:java@GetMapping('/date')public String date(Model model) {  return 'date';}</p>
<h3>3. 创建 Thymeleaf 模板</h3>
<p>在 <code>resources/templates</code> 目录下创建一个名为 <code>date.html</code> 的 Thymeleaf 模板文件,并添加以下代码:html<!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></p>
<h3>4. 处理表单提交</h3>
<p>在 Controller 类中添加一个 <code>PostMapping</code> 方法,用于接收提交的日期数据:java@PostMapping('/date')public String dateSubmit(@RequestParam('date') @DateTimeFormat(pattern = 'yyyy-MM-dd') Date date, Model model) {  model.addAttribute('date', date);  return 'date'</p>
Spring Boot Thymeleaf 实现日期选择器

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

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