Spring Boot+JSP Todo应用:JSP无法显示Todo列表求助
问题解决:Spring Boot + JSP Todo列表无法显示
核心错误点
- 控制器输出格式强制为JSON:
@GetMapping的produces = {"application/json"}会让接口默认返回JSON数据,而非渲染JSP视图,导致模型数据无法传递到页面。 - JSTL标签未声明:JSP中使用的
<c:forEach>和<fmt:formatDate>标签属于JSTL规范,未引入标签库会导致标签无法解析执行。 - 页面HTML结构错误:表格存在重复列输出,且标签嵌套不规范,导致页面渲染异常。
- 缺少JSTL依赖:Spring Boot默认不包含JSTL依赖,需手动引入才能使用相关标签。
修正后的代码
1. HomeController.java
移除produces属性,同时修正静态控制器方法问题:
package com.toDoApp.ToDoApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @Autowired ToDoRepo repo; @RequestMapping("/") public String home() // 移除static修饰,Spring无法管理静态控制器方法 { return "Home"; } @GetMapping(path = "/list-todos") public String toDoView(Model m) { m.addAttribute("todolist", repo.findAll()); return "ToDoView"; } }
2. ToDoView.jsp
引入JSTL标签库,修正页面结构:
<%@ include file="header.jsp"%> <%@ include file="navigation.jsp"%> <!-- 引入JSTL核心标签库 --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- 引入JSTL格式化标签库 --> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <div class="container"> <div> <a type="button" class="btn btn-primary btn-md" href="/add-todo">Add Todo</a> </div> <br> <div class="panel panel-primary"> <div class="panel-heading"> <h3>List of TODO's</h3> </div> <div class="panel-body"> <table class="table table-striped"> <thead> <tr> <th width="40%">Description</th> <th width="40%">Target Date</th> <th width="20%"></th> </tr> </thead> <tbody> <c:forEach items="${todolist}" var="todo"> <tr> <td>${todo.description}</td> <td><fmt:formatDate value="${todo.toDoDate}" pattern="dd/MM/yyyy" /></td> <td> <a type="button" class="btn btn-success" href="/update-todo?id=${todo.id}">Update</a> <a type="button" class="btn btn-warning" href="/delete-todo?id=${todo.id}">Delete</a> </td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> <%@ include file="footer.jsp"%>
修正说明:移除多余的
${todolist}输出,删除重复列,统一使用EL属性访问语法(${todo.toDoDate}替代${todo.getToDoDate()})
3. 添加JSTL依赖
Maven(pom.xml):
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
Gradle(build.gradle):
implementation 'javax.servlet:jstl:1.2'
验证步骤
- 重启Spring Boot应用
- 访问
/list-todos路径 - 检查页面是否正常渲染Todo列表,可通过查看页面源代码确认JSTL标签是否被正确解析(不会显示原始标签)
内容的提问来源于stack exchange,提问作者MUKUL SHARMA
相关产品推荐
相关产品推荐

