一、配置文件
web.xml,springmvc.xml,这些配置文件和查询所有雇员信息的配置相同。
二、请求测试页面
第一步,跳转到添加雇员信息页
浏览器访问链接: http://localhost:8080/springmvc-2/doGetEmps
或者网页中,插入超链接:
<body> <a href="doAddEmp">转到雇员信息页</a> </body>
第二步,显示添加雇员信息页
addEmp.jsp
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
1. WHY 使用 form 标签呢 ?
可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显
2. 注意:
可以通过 modelAttribute 属性指定绑定的模型属性,
若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean
如果该属性值也不存在,则会发生错误。
大白话:form:form 表单标签,在springmvc中是一定要回显的,哪怕是第一次也要支持回显。
所以第一次请求时,form:form 表单标签会从 request域中的 关键字中查找 默认值是command(如果 form:form标签 指定modelAttribute="XXX",则按照XXX关键字来) 查看属性值,用来填充表单值。
-->
<form:form action="emp" method="post" modelAttribute="employee">
<!-- path标签对应 html表单标签的 name属性值,支持级联 如 path="department.id" -->
LastName:<form:input path="lastName" />
<br>
Email:<form:input path="email" />
<%
Map<String, String> genders = new HashMap();
genders.put("1", "Male");
genders.put("0", "Female");
request.setAttribute("genders", genders);
%>
<br>
Gender:<form:radiobuttons path="gender" items="${genders}" />
<br>
Department:<form:select path="department.id" items="${departments}" itemLabel="departmentName" itemValue="id"></form:select>
<br>
<input type="submit" value="submit" />
</form:form>
</body>
</html>
总结:addEmp.jsp中用了表单标签,而springmvc中需要表单标签回显值,默认从request中查找command属性,匹配表单值。当然如果,表单标签有@ModelAttribute,就按照@ModelAttribute指定的属性值,优先查找并匹配表单值。如果没有匹配值,就报错了。
三、编辑控制器
在查询所有雇员的信息的控制器的基础上,添加:
//跳转到添加雇员信息页面
@RequestMapping("/doAddEmp")
public String doAddEmp(Map<String, Object> map){
//为了提供在添加页面,部门列表
map.put("departments",departmentDao.getDepartments());
//为了提供雇员信息的回显值,添加一个空的雇员信息
map.put("employee", new Employee());
return "addEmp";
}
//处理添加雇员请求,并重定向到 @RequestMapping("/emps")
@RequestMapping(value="/emp", method=RequestMethod.POST)
public String addEmp(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}
四、请求结果响应页
重定向到了 showGetEmps.jsp