版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38016931/article/details/81989345
一、需求
点击表格中的修改链接修改某条学生信息,点击链接首先跳转到之前使用的添加页面,动态地做出相应的修改,然后点击修改键修改信息后重定向到list界面显示所有信息!
跳转到input.jsp界面,url为stu/{id},请求方式为get!
修改操作 url为stu,请求方式为put!
二、代码
在显示所有信息界面添加修改超链接:
<c:forEach items="${requestScope.list}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.gender?"male":"female"}</td>
<td>${stu.age}</td>
<td>${stu.school.name}</td>
<td><a href="#" onclick="postForm(${stu.id})">删除</a>|
<a href="stu/${stu.id}">修改</a></td>
</tr>
</c:forEach>
为了实现修改这个功能,在类方法中也做了很多修改:
首先是在StudentDao中的修改,添加了一个静态私有变量
idIncreaseAutomatically
每次数据库中新增一个student这个变量就加一,这样我们就保证了学号的独一性,而且还在saveStudent方法中判断数据库中有没有数据信息和要新增的学生的学号一致,有的话就做修改,没有则添加
private static int idIncreaseAutomatically = 5;
public void saveStudent(Student student) {
/* if student'id has not been initialize but other attributes in it have been initialize*/
if (student.getId() == 0) {
student.setId(idIncreaseAutomatically++);
} else {
deleteStudentById(student.getId());
}
map.put(student.getId(), student);
}
然后添加映射方法:
/* jump to input.jsp to change student's information */
@RequestMapping(value = "/stu/{id}", method = RequestMethod.GET)
public String input(@PathVariable(value = "id") Integer id, Map<String, Object> map) {
map.put("student", studentDao.getStudentById(id));
map.put("SchoolList", schoolDao.getAllSchool());
return "input";
}
然后我在input.jsp上也做了修改,添加了通过判断姓名是否为空来决定添加信息功能还是修改信息功能:
<form:form action="/stu" method="post" modelAttribute="student">
<%-- not change page --%>
<c:if test="${empty requestScope.student.name}">
name:<form:input path="name"/><br>
</c:if>
<%--change page--%>
<c:if test="${not empty requestScope.student.name}">
<form:hidden path="name"/>
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT">
</c:if>
age:<form:input path="age"/><br>
gender:<form:radiobuttons path="gender" items="${genders}"/> <br>
school:<form:select path="school.id" items="${requestScope.SchoolList}" itemLabel="name" itemValue="id"/>
<%--change page--%>
<c:if test="${not empty requestScope.student.name}">
<input type="submit" value="保存修改">
</c:if>
<%-- not change page --%>
<c:if test="${empty requestScope.student.name}">
<input type="submit" value="添加信息">
</c:if>
</form:form>
最后添加修改功能的映射方法:
/* change one's information */
@RequestMapping(value = "/stu", method = RequestMethod.PUT)
public String change(Student student) {
/* it is the solution of the question that input.jsp only give student'school id value but no name value */
School school = schoolDao.getSchoolById(student.getSchool().getId());
student.setSchool(school);
studentDao.saveStudent(student);
return "redirect:stus";
}
三、运行效果
点击添加后的input.jsp:
修改功能的input.jsp:
在表单上修改信息点击保存修改:
修改成功!
四、心得
SpringMVC的REST风格CRUD写完,觉得还是挺简单的,没有遇到什么大bug,虽然代码简单,但我觉得所谓的REST风格是真的很优秀啊,用起来的感觉真的是很棒,只要稍微添加上数据库部分就是一个小系统了。
CRUD四篇文章每一篇都有新知识,有关SpringMVC或者其他的都让我受益很多,SpringMVC继续学吧!
困~~睡觉。。