项目结构
web.xml和spring-mvc.xml的配置同笔记一:https://blog.csdn.net/Shinka_YXS/article/details/86076515
web.xml配置分发servlet、spring-mvc配置文件、将初始界面改为index.jsp、
spring-mvc.xml配置使用注解的包、视图解析器、
Student类设置id name age三个属性及其get set方法、
StudentController
//@RequestMapping为了区分哪个模块
@Controller
@RequestMapping("/student")
public class StudentController {
private static List<Student> studentList=new ArrayList<Student>();
static{
studentList.add(new Student(1,"张三",11));
studentList.add(new Student(2,"李四",12));
studentList.add(new Student(3,"王五",13));
}
//最终请求是 项目/student/list
@RequestMapping("/list")
public ModelAndView list(){ //返回模型和视图
ModelAndView mav=new ModelAndView();
mav.addObject("studentList", studentList);//该数据页面可以提取到,底层转发将其放在request里面、
mav.setViewName("student/list"); //设置视图名称
return mav;
}
//@RequestParam接收请求参数、赋值给 String id、参数required=false表示非必需
@RequestMapping("/preSave")
public ModelAndView preSave(@RequestParam(value="id",required=false) String id){
ModelAndView mav=new ModelAndView();
if(id!=null){
mav.addObject("student", studentList.get(Integer.parseInt(id)-1));
mav.setViewName("student/update");
}else{
mav.setViewName("student/add");
}
return mav;
}
}
list.jsp中引入jstl、
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!-- 以下代码在body中 -->
<!-- 最好用绝对地址 -->
<a href="${pageContext.request.contextPath}/student/preSave.do">添加学生</a>
<table>
<tr>
<th>编号</th><th>姓名</th><th>年龄</th><th>操作</th>
</tr>
<c:forEach var="student" items="${studentList}">
<tr>
<td>${student.id }</td>
<td>${student.name }</td>
<td>${student.age }</td>
<!-- 修改操作要传递参数id -->
<td><a href="${pageContext.request.contextPath}/student/preSave.do?id=${student.id}">修改</a></td>
</tr>
</c:forEach>
</table>
add.jsp
<!-- 以下代码在body中 -->
<form action="student/save.do" method="post">
<table>
<tr>
<th colspan="2">学生添加</th>
</tr>
<tr>
<td>姓名</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
update.jsp
<!-- 以下代码在body中 -->
<form action="student/save.do" method="post">
<table>
<tr>
<th colspan="2">学生修改</th>
</tr>
<tr>
<td>姓名</td>
<td><input type="text" name="name" value="${student.name }"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age" value="${student.age }"/></td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="id" value="${student.id }"/>
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>