1.
1.list.jsp <a href="emp">Add New Employee</a> 2.input.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> <!-- why使用form标签 1.可以更快速的开发出表单页面,而且可以更加方便的进行表单值的回显; --> <form:form action="emp" method="POST" modelAttribute="employee"> <!-- path属性对应html表单标签的name属性值 --> LastName:<form:input path="lastName" /> <br> email:<form:input path="email" /> <br> <% Map<String, String> genders = new HashMap(); genders.put("1", "male"); genders.put("0", "Female"); request.setAttribute("genders", genders); %> <!-- delimiter="<br>" 按照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>
2.java代码
package com.yikuan.springmvc.crud.handlers; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.yikuan.springmvc.crud.dao.DepartmentDao; import com.yikuan.springmvc.crud.dao.EmployeeDao; import com.yikuan.springmvc.crud.entities.Employee; @Controller public class EmployeeHandler { @Autowired private EmployeeDao employeeDao; @Autowired private DepartmentDao departmentDao; @RequestMapping(value="/emp",method=RequestMethod.POST) public String save(Employee employee){ employeeDao.save(employee); return "redirect:/emps"; } @RequestMapping(value="emp",method=RequestMethod.GET) public String input(Map<String,Object> map){ map.put("departments", departmentDao.getDepartments()); map.put("employee", new Employee()); return "input"; } @RequestMapping("/emps") public String list(Map<String, Object> map){ map.put("employees", employeeDao.getAll()); return "list"; } }
3.结果