【发布时间】:2017-01-18 06:49:50
【问题描述】:
我只是在 Spring MVC 中创建一个 CRUD 应用程序。我想编辑学生详细信息。我创建了一种用于添加学生的表格。如何使用相同的表单来填充学生详细信息以进行编辑?
控制器
@RequestMapping(value="/add", method = RequestMethod.GET)
public String addStudent(@RequestParam("studentName") String name,@RequestParam("studentId") String studId){
System.out.println("Student Id : "+ studId);
System.out.println("Student "+name+" added");
list.add(name);
return "redirect:get";
}
@RequestMapping(value="/edit/${index}", method = RequestMethod.GET)
public String editStudent(@PathVariable("index") int index, Model model){
System.out.println("Edit Student with Index " + index);
model.addAttribute("studentId",index);
model.addAttribute("studentName",list.get(index));
return "student";
}
表格
<c:url value="/students/add" var="addStudentAction"></c:url>
<form action="${addStudentAction}" method="get">
<input type="hidden" name="studentId">
<input type="text" name="studentName"></input>
<input type="submit" name="submit" value="Add Student" />
</form>
我想在editStudent方法的模型中设置的表单字段中设置studentId和studentName。
【问题讨论】:
-
仅供参考:创建和编辑最好使用 POST 方法而不是 GET。
-
关键是modelAttribute的使用。看看这里,例如arquitecturajava.com/spring-mvc-modelattribute
标签: java spring spring-mvc