今天写基于SSM框架的程序,用到了<form:select>。由于一开始遇到了问题,所以在这里加以记录,供以后查看。
直接看jsp页面的代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
3 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
6 <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
9 </head>
<body>
<form:form method="post" modelAttribute="employee">
姓名:<form:input path="lastName"/><br>
邮箱:<form:input path="email"/><br>
性别:<form:input path="gender"/><br>
部门:<form:select path="department" items="${departments}" itemValue="id" itemLabel="departmentName"></form:select>
</form:form>
</body>
18 </html>
1.由于我们要引用Spring封装的form标签,所以一开始要配置引用标签:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
2.对于
<form:form method="post" modelAttribute="employee">
其modelAttribute="employee"中的employee是 在controller层中跳转到该页面的方法中 绑定的对象。 即:
@RequestMapping("/add")
public ModelAndView toAddPage(){
ModelAndView mView=new ModelAndView();
mView.addObject("employee",new Employee());
mView.setViewName("add-stu");
mView.addObject("departments", departmentDao.getDepartments());
return mView;
}
3对于
部门:<form:select path="department.id" items="${departments}" itemValue="id" itemLabel="departmentName"></form:select>
path="department" 为后续提取本方法中的对象预留了接口(类似于<input type="text" name="email">中的name)
items="${departments}" 表示你要遍历的列表
itemValue="id" 表示列表选项中的value属性(当对下拉列表做出选择时后台传递的数据)【可能有些偏颇,欢迎指教】
itemLabel="departmentName" 表示页面列表中现实的属性值
实现结果:
查看页面源码: