如何通过Spring Boot从数据库获取学生数量并在Bootstrap卡片展示?
修复步骤
1. 修正后端代码
仓库层(Student Repository)
原代码中count(e)返回Long类型,但方法声明为返回String会导致类型转换错误,需修改为:
@Query("select count(e) from Student e") public Long StudentsNBR();
控制器层(Student Controller)
直接返回Long类型,Spring会自动序列化为JSON格式,方便前端解析:
@GetMapping("/numberStudent") @ResponseBody public Long getStudentNumber(){ return studentRepository.StudentsNBR(); }
2. 完善前端AJAX逻辑与页面结构
在Bootstrap卡片中添加数量展示占位元素,同时为AJAX请求添加成功回调更新页面:
<div class="col-sm"> <div class="card bg-light" style="width: 18rem;"> <img class="card-img-top" src="https://cdn.discordapp.com/attachments/557595531526799390/1033961333584052224/spring.gif" style="height: 180px;"> <div class="card-body"> <div class="p-1 mb-2 bg-dark text-white"> <h5 class="card-title" align="center">Spring BOOT</h5> </div> <!-- 学生数量展示占位元素 --> <p class="card-text" align="center">学生总数: <span id="studentCount">-</span></p> <script> jQuery(function($) { $.ajax({ type: "GET", url: "/numberStudent", success: function(response) { // 更新页面显示的学生数量 $("#studentCount").text(response); }, error: function() { // 请求失败时的提示 $("#studentCount").text("加载失败"); } }); }); </script> </div> </div> </div>
关键修改说明
- 添加
<span id="studentCount">-</span>作为数量展示的占位符,初始显示-表示加载中。 - 为AJAX请求添加
success回调,成功获取数据后将数字插入到占位符中。 - 增加
error回调处理请求失败的情况,提升用户体验。
内容的提问来源于stack exchange,提问作者el idrissi oussama
相关产品推荐
相关产品推荐

