我一直在研究构建简单的Spring Web应用程序的教程。
在应用程序中,我在JSP视图中成功显示了从CRUD存储库显示的任务列表。在此任务列表视图中,我可以选择更新单个任务。
问题在于更新表单视图未在输入值中检索任务属性。我没有收到任何错误,所以我对丢失的内容感到困惑。
由于我可以在控制台中打印属性,因此控制器正在获取属性。
控制器:
@GetMapping("/update-tasks")
public String updateTasks(@RequestParam int id, HttpServletRequest req) {
req.setAttribute("tasks", taskService.findTask(id));
System.out.println(taskService.findTask(id).getDescription()); ----> this is just to test if I was getting the description attribute.
req.setAttribute("mode", "MODE_UPDATE");
return "index";
}
JSP更新表单视图:
<c:when test="${mode == 'MODE_NEW'||mode == 'MODE_UPDATE' }" >
<div class="container text-center">
<h3>Manage Task</h3>
<hr>
<form class="form-horizontal" method="POST" action="save-task">
<input type="hidden" name="id" value="${task.id}"/>
<div class="form-group row">
<label class="control-label col-md-3">Name</label>
<div class="col-md-7">
<input type="text" class="form-control" name="name" value="${task.name}"/>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-3">Description</label>
<div class="col-md-7">
<input type="text" class="form-control" name="description" value="${task.description}"/>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-3">Finished</label>
<div class="col-md-7">
<div class="form-row">
<input type="radio" class="col-sm-1" name="finished" value="true"/>
<div class="col-sm-1">Yes</div>
<input type="radio" class="col-sm-1" name="finished" value="false" checked/>
<div class="col-sm-1">No</div>
</div>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Save"/>
</div>
</form>
</div>
</c:when>
JSP任务列表视图。 JSP的这一部分确实适用于JSTL:
<c:when test="${mode == 'MODE_TASKS' }" >
<div class="container text-center" id="tasksDiv">
<h3>My Tasks</h3>
<hr>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover"">
<thead>
<tr class="table-dark">
<th>Id</th>
<th>Name</th>
<th>Description</th>
<th>Date created</th>
<th>Finished</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach items="${tasks}" var="task" >
<tr>
<td>${task.id}</td>
<td>${task.name}</td>
<td>${task.description}</td>
<td><fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${task.dateCreated}"/></td>
<td>${task.finished}</td>
<td><a href="update-tasks?id=${task.id}"><i class="fa fa-pencil" aria-hidden="true"></i></a></td>
<td><a href="delete-tasks?id=${task.id}"><i class="fa fa-trash-o" aria-hidden="true"></i></a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</c:when>
答案 0 :(得分:0)
解决方案
我使用ModelAndView对象将值从控制器传递给视图,所以我的更新控制器现在看起来像这样:
@GetMapping("/update-tasks")
public ModelAndView updateTasks(@RequestParam int id) {
ModelAndView mv = new ModelAndView();
mv.addObject("task", taskService.findTask(id));
mv.addObject("mode", "MODE_UPDATE");
mv.setViewName("index");
return mv;
}