本文将详细讲解如何使用 SpringBoot、JPA 和 Thymeleaf 实现前端页面数据删除功能。

前端代码

<a th:href="@{/delete/{id}(id=${data.id})}" onclick="return confirm('确定要删除吗?')">删除</a>

后端代码

Controller 层

@RequestMapping("/delete/{id}")
public String delete(@PathVariable("id") Long id) {
    // 调用 Service 层的删除方法
    userService.delete(id);
    // 重定向到列表页面
    return "redirect:/list";
}

Service 层

public void delete(Long id) {
    userRepository.deleteById(id);
}

其中,userRepository 为 JPA 的接口,继承了 CrudRepository,因此可以直接调用其提供的删除方法。在 Controller 中,@PathVariable("id") 注解表示从路径中获取 id 参数。在前端代码中,使用 Thymeleaf 的 @{} 语法构造删除链接,同时使用 confirm() 函数弹出确认框以防止误删。

SpringBoot + JPA 使用 Thymeleaf 实现数据删除

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

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