在 Thymeleaf 中,可以使用 th:field 属性和 th:format 属性来实现日期框的显示。以下是一个示例代码:

<form th:object="${dateModel}" th:action="@{/save}" method="post">
    <input type="text" th:field="*{date}" th:format="'yyyy-MM'" />
    <button type="submit">保存</button>
</form>

在上面的代码中,我们假设有一个名为 dateModel 的后端对象,其中包含一个名为 date 的日期属性。通过使用 th:field="*{date}",我们将日期属性绑定到输入框中。使用 th:format="'yyyy-MM'" 可以指定日期的格式为年月。

在后端 Spring Boot 代码中,需要确保在 Controller 中设置 dateModel 对象,并将其添加到 Model 中,以便在 Thymeleaf 模板中使用。以下是一个示例代码:

@Controller
public class DateController {

    @GetMapping("/form")
    public String showForm(Model model) {
        DateModel dateModel = new DateModel();
        model.addAttribute("dateModel", dateModel);
        return "dateForm";
    }

    @PostMapping("/save")
    public String saveDate(@ModelAttribute("dateModel") DateModel dateModel) {
        // 处理保存逻辑
        return "redirect:/form";
    }
}

在上面的代码中,我们在 GET 请求的处理方法中创建了一个 DateModel 对象,并将其添加到 Model 中。在 POST 请求的处理方法中,我们使用 @ModelAttribute 注解将提交的表单数据绑定到 DateModel 对象中。

请根据你的具体需求修改上述代码,并确保在 Spring Boot 应用程序中正确配置 Thymeleaf。

Thymeleaf 日期框仅显示年月:前端实现与 Spring Boot 后端集成

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

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