员工列表 员工添加: 员工修改 员工删除-点击完成删除来到列表页面
增删改查的URL地址; /资源名/资源标识 /emp/1 GET:查询id为1的员工 /emp/1 PUT:更新id为1的员工 /emp/1 DELETE:删除id为1的员工 /emp POST:新增员工; /emps GET:查询所有员工
员工列表展示;查询所有员工; 员工列表展示:访问index.jsp----直接发送/emps------控制器查询所有员工------放在请求域中-----转发到list页面展示 员工添加: 在list页面点击“”员工添加“”----(查询出所有的部门信息要展示在页面)----来到添加页面(add.jsp)--------输入员工数据--------点击保存(/emp )------处理器收到员工保存请求(保存员工)--------保存完成以后还是来到列表页面;
- 通过 SpringMVC的表单标签可以实现将模型数据中的属性和 HTML 表单元素相绑定,以实现表单数据更便捷编辑和表单值的回显
用了表单标签的页面可能会报这个错误; 请求域中没有一个command类型的对象; 来到页面之前一定要给请求域中放这个对象;
代码实例
Department.java:
1 package com.atguigu.bean; 2 3 public class Department { 4 5 private Integer id; 6 private String departmentName; 7 8 public Department() { 9 } 10 11 public Department(int i, String string) { 12 this.id = i; 13 this.departmentName = string; 14 } 15 16 public Integer getId() { 17 return id; 18 } 19 20 public void setId(Integer id) { 21 this.id = id; 22 } 23 24 public String getDepartmentName() { 25 return departmentName; 26 } 27 28 public void setDepartmentName(String departmentName) { 29 this.departmentName = departmentName; 30 } 31 32 @Override 33 public String toString() { 34 return "Department [id=" + id + ", departmentName=" + departmentName + "]"; 35 } 36 37 }
Employee.java:
1 package com.atguigu.bean; 2 3 import java.util.Date; 4 5 public class Employee { 6 7 private Integer id; 8 private String lastName; 9 10 private String email; 11 //1 male, 0 female 12 private Integer gender; 13 14 private Department department; 15 16 public Integer getId() { 17 return id; 18 } 19 20 public void setId(Integer id) { 21 this.id = id; 22 } 23 24 public String getLastName() { 25 return lastName; 26 } 27 28 public void setLastName(String lastName) { 29 this.lastName = lastName; 30 } 31 32 public String getEmail() { 33 return email; 34 } 35 36 public void setEmail(String email) { 37 this.email = email; 38 } 39 40 public Integer getGender() { 41 return gender; 42 } 43 44 public void setGender(Integer gender) { 45 this.gender = gender; 46 } 47 48 public Department getDepartment() { 49 return department; 50 } 51 52 public void setDepartment(Department department) { 53 this.department = department; 54 } 55 56 public Employee(Integer id, String lastName, String email, Integer gender, 57 Department department) { 58 super(); 59 this.id = id; 60 this.lastName = lastName; 61 this.email = email; 62 this.gender = gender; 63 this.department = department; 64 } 65 66 public Employee() { 67 } 68 69 @Override 70 public String toString() { 71 return "Employee [id=" + id + ", lastName=" + lastName + ", email=" 72 + email + ", gender=" + gender + ", department=" + department 73 + "]"; 74 } 75 76 77 }
DepartmentDao.java:
1 package com.atguigu.dao; 2 3 import java.util.Collection; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import org.springframework.stereotype.Repository; 8 9 import com.atguigu.bean.Department; 10 11 /** 12 * 操作部门的dao 13 * @author lfy 14 * 15 */ 16 @Repository 17 public class DepartmentDao { 18 19 private static Map<Integer, Department> departments = null; 20 21 static{ 22 departments = new HashMap<Integer, Department>(); 23 24 departments.put(101, new Department(101, "D-AA")); 25 departments.put(102, new Department(102, "D-BB")); 26 departments.put(103, new Department(103, "D-CC")); 27 departments.put(104, new Department(104, "D-DD")); 28 departments.put(105, new Department(105, "D-EE")); 29 } 30 31 /** 32 * 返回所有的部门 33 * @return 34 */ 35 public Collection<Department> getDepartments(){ 36 return departments.values(); 37 } 38 39 /** 40 * 按照部门id查询部门 41 * @param id 42 * @return 43 */ 44 public Department getDepartment(Integer id){ 45 return departments.get(id); 46 } 47 48 }
EmployeeDao.java:
1 package com.atguigu.dao; 2 3 import java.util.Collection; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Repository; 9 10 import com.atguigu.bean.Department; 11 import com.atguigu.bean.Employee; 12 13 14 /** 15 * EmployeeDao:操作员工 16 * @author lfy 17 * 18 */ 19 @Repository 20 public class EmployeeDao { 21 22 private static Map<Integer, Employee> employees = null; 23 24 @Autowired 25 private DepartmentDao departmentDao; 26 27 static{ 28 employees = new HashMap<Integer, Employee>(); 29 30 employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA"))); 31 employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB"))); 32 employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC"))); 33 employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD"))); 34 employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE"))); 35 } 36 37 //初始id 38 private static Integer initId = 1006; 39 40 /** 41 * 员工保存/更新二合一方法; 42 * @param employee 43 */ 44 public void save(Employee employee){ 45 if(employee.getId() == null){ 46 employee.setId(initId++); 47 } 48 49 //根据部门id单独查出部门信息设置到员工对象中,页面提交的只需要提交部门的id 50 employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId())); 51 employees.put(employee.getId(), employee); 52 } 53 54 /** 55 * 查询所有员工 56 * @return 57 */ 58 public Collection<Employee> getAll(){ 59 return employees.values(); 60 } 61 62 /** 63 * 按照id查询某个员工 64 * @param id 65 * @return 66 */ 67 public Employee get(Integer id){ 68 return employees.get(id); 69 } 70 71 /** 72 * 删除某个员工 73 * @param id 74 */ 75 public void delete(Integer id){ 76 employees.remove(id); 77 } 78 }
EmployeeController.java:
1 package com.atguigu.controller; 2 3 import java.util.Collection; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.ModelAttribute; 9 import org.springframework.web.bind.annotation.PathVariable; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 import org.springframework.web.bind.annotation.RequestMethod; 12 import org.springframework.web.bind.annotation.RequestParam; 13 14 import com.atguigu.bean.Department; 15 import com.atguigu.bean.Employee; 16 import com.atguigu.dao.DepartmentDao; 17 import com.atguigu.dao.EmployeeDao; 18 19 @Controller 20 public class EmployeeController { 21 22 @Autowired 23 EmployeeDao employeeDao; 24 25 @Autowired 26 DepartmentDao departmentDao; 27 28 /** 29 * 查询所有员工 30 * 31 * @return 32 */ 33 @RequestMapping("/emps") 34 public String getEmps(Model model) { 35 Collection<Employee> all = employeeDao.getAll(); 36 model.addAttribute("emps", all); 37 return "list"; 38 } 39 40 @RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE) 41 public String deleteEmp(@PathVariable("id")Integer id){ 42 employeeDao.delete(id); 43 return "redirect:/emps"; 44 } 45 46 /** 47 * 查询员工,来到修改页面回显 48 * 49 * @param id 50 * @param model 51 * @return 52 */ 53 @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET) 54 public String getEmp(@PathVariable("id") Integer id, Model model) { 55 // 1、查出员工信息 56 Employee employee = employeeDao.get(id); 57 // 2、放在请求域中 58 model.addAttribute("employee", employee); 59 // 3、继续查出部门信息放在隐含模型中 60 Collection<Department> departments = departmentDao.getDepartments(); 61 model.addAttribute("depts", departments); 62 return "edit"; 63 } 64 65 @RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT) 66 public String updateEmp(@ModelAttribute("employee")Employee employee/* ,@PathVariable("id")Integer id */) { 67 System.out.println("要修改的员工:" + employee); 68 // xxxx 更新保存二合一; 69 employeeDao.save(employee); 70 return "redirect:/emps"; 71 } 72 73 @ModelAttribute 74 public void myModelAttribute( 75 @RequestParam(value = "id", required = false) Integer id,Model model) { 76 if (id != null) { 77 Employee employee = employeeDao.get(id); 78 model.addAttribute("employee", employee); 79 } 80 System.out.println("hahha "); 81 } 82 83 /** 84 * 保存员工 85 * 86 * @param employee 87 * @return 88 */ 89 @RequestMapping(value = "/emp", method = RequestMethod.POST) 90 public String addEmp(Employee employee) { 91 System.out.println("要添加的员工:" + employee); 92 employeeDao.save(employee); 93 // 返回列表页面;重定向到查询所有员工的请求 94 return "redirect:/emps"; 95 } 96 97 /** 98 * 去员工添加页面,去页面之前需要查出所有部门信息,进行展示的 99 * 100 * @return 101 */ 102 @RequestMapping("/toaddpage") 103 public String toAddPage(Model model) { 104 // 1、先查出所有部门 105 Collection<Department> departments = departmentDao.getDepartments(); 106 // 2、放在请求域中 107 model.addAttribute("depts", departments); 108 model.addAttribute("employee", new Employee()); 109 // 3、去添加页面 110 return "add"; 111 } 112 113 }
HelloController.java:
1 package com.atguigu.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @Controller 7 public class HelloController { 8 9 @RequestMapping("/hello") 10 public String handle01(){ 11 return "success"; 12 } 13 14 }
springmvc.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 9 10 <!-- 扫描所有组件 --> 11 <context:component-scan base-package="com.atguigu"></context:component-scan> 12 13 <!-- 配置一个视图解析器 ;能帮我们拼接页面地址--> 14 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 15 <property name="prefix" value="/WEB-INF/pages/"></property> 16 <property name="suffix" value=".jsp"></property> 17 </bean> 18 19 <!--SpringMVC管理国际化资源文件,配置一个资源管理器 id必须是messageSource--> 20 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 21 <!--basename指定基础名--> 22 <property name="basename" value="i18n"></property> 23 </bean> 24 25 <!-- 默认前端控制器是拦截所有资源(除过jsp),js文件就404了;要js文件的请求是交给tomcat处理的 26 http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js --> 27 <!-- 告诉SpringMVC,自己映射的请求就自己处理,不能处理的请求直接交给tomcat --> 28 <!-- 静态资源能访问,动态映射的请求就不行 --> 29 <mvc:default-servlet-handler/> 30 <!-- springmvc可以保证动态请求和静态请求都能访问 --> 31 <mvc:annotation-driven></mvc:annotation-driven> 32 </beans>
web.xml:
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 6 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 7 id="WebApp_ID" version="3.0"> 8 <display-name>7.SpringMVC_crud</display-name> 9 <welcome-file-list> 10 <welcome-file>index.jsp</welcome-file> 11 </welcome-file-list> 12 13 <!-- The front controller of this Spring Web application, 14 responsible for handling all application requests --> 15 <servlet> 16 <servlet-name>springDispatcherServlet</servlet-name> 17 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 18 <init-param> 19 <!-- contextConfigLocation:指定SpringMVC配置文件位置 --> 20 <param-name>contextConfigLocation</param-name> 21 <param-value>classpath:springmvc.xml</param-value> 22 </init-param> 23 <load-on-startup>1</load-on-startup> 24 </servlet> 25 26 <!-- Map all requests to the DispatcherServlet for handling --> 27 <servlet-mapping> 28 <servlet-name>springDispatcherServlet</servlet-name> 29 <url-pattern>/</url-pattern> 30 </servlet-mapping> 31 32 <!-- 配置一个字符编码的Filter;一定注意:字符编码filter一般都在其他Filter之前; --> 33 <!--配置字符集编码的Filter--> 34 <filter> 35 <filter-name>CharacterEncodingFilter</filter-name> 36 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 37 <!-- encoding:指定解决POST请求乱码 --> 38 <init-param> 39 <param-name>encoding</param-name> 40 <!--不区分大小写--> 41 <param-value>utf-8</param-value> 42 </init-param> 43 <init-param> 44 <!-- forceEncoding:顺手解决响应乱码;response.setCharacterEncoding(this.encoding); --> 45 <param-name>forceEncoding</param-name> 46 <param-value>true</param-value> 47 </init-param> 48 </filter> 49 <filter-mapping> 50 <filter-name>CharacterEncodingFilter</filter-name> 51 <url-pattern>/*</url-pattern> 52 </filter-mapping> 53 54 <!--支持Rest风格的Filter(开启PUT、DELETE请求)--> 55 <filter> 56 <filter-name>HiddenHttpMethodFilter</filter-name> 57 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 58 </filter> 59 <filter-mapping> 60 <filter-name>HiddenHttpMethodFilter</filter-name> 61 <url-pattern>/*</url-pattern> 62 </filter-mapping> 63 <!-- 使用SpringMVC前端控制器写完就直接写字符编码过滤器; 64 Tomcat一装上,上手就是server.xml的8080处添加URIEncoding="UTF-8" 65 --> 66 67 </web-app>index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!-- 访问项目就要展示员工列表页面 --> 4 <jsp:forward page="/emps"></jsp:forward>
list.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <% 7 pageContext.setAttribute("ctp", request.getContextPath()); 8 %> 9 <head> 10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 11 <title>员工列表</title> 12 <script type="text/javascript" src="${ctp }/scripts/jquery-1.9.1.min.js"></script> 13 </head> 14 <body> 15 16 <h1>员工列表</h1> 17 <table border="1" cellpadding="5" cellspacing="0"> 18 <tr> 19 <th>ID</th> 20 <th>lastName</th> 21 <th>email</th> 22 <th>gender</th> 23 <th>departmentName</th> 24 <th>EDIT</th> 25 <th>DELETE</th> 26 </tr> 27 <c:forEach items="${emps }" var="emp"> 28 <tr> 29 <td>${emp.id }</td> 30 <td>${emp.lastName}</td> 31 <td>${emp.email }</td> 32 <td>${emp.gender==0?"女":"男" }</td> 33 <td>${emp.department.departmentName }</td> 34 <td><a href="${ctp }/emp/${emp.id }">edit</a></td> 35 <td><a href="${ctp }/emp/${emp.id }" class="delBtn">delete</a></td> 36 </tr> 37 </c:forEach> 38 </table> 39 <a href="${ctp }/toaddpage">添加员工</a> 40 41 <form id="deleteForm" action="${ctp }/emp/${emp.id }" method="post"> 42 <input type="hidden" name="_method" value="DELETE" /> 43 </form> 44 <script type="text/javascript"> 45 $(function(){ 46 $(".delBtn").click(function(){ 47 //0、确认删除? 48 //1、改变表单的action指向 49 $("#deleteForm").attr("action",this.href); 50 //2、提交表单 51 $("#deleteForm").submit(); 52 return false; 53 }); 54 }); 55 </script> 56 </body> 57 </html>
add.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>Insert title here</title> 10 </head> 11 <body> 12 <h1>员工添加</h1> 13 <!-- 14 表单标签; 15 通过 SpringMVC的表单标签可以实现将模型数据中的属性和 HTML 表单元素相绑定, 16 以实现表单数据更便捷编辑和表单值的回显 17 1)、SpringMVC认为,表单数据中的每一项最终都是要回显的; 18 path指定的是一个属性;这个属性是从隐含模型(请求域中取出的某个对象中的属性); 19 path指定的每一个属性,请求域中必须有一个对象,拥有这个属性; 20 这个对象就是请求域中的command; 21 modelAttribute="": 22 1)、以前我们表单标签会从请求域中获取一个command对象;把这个对象中的每一个属性对应的显示出来 23 2)、可以告诉SpringMVC不要去取command的值了,我放了一个modelAttribute指定的值; 24 取对象用的key就用我modelAttribute指定的; 25 --> 26 <% 27 pageContext.setAttribute("ctp", request.getContextPath()); 28 %> 29 <form:formaction="${ctp }/emp"modelAttribute="employee" method="POST"> 30 <!-- path就是原来html-input的name项:需要写 31 path: 32 1)、当做原生的name项 33 2)、自动回显隐含模型中某个对象对应的这个属性的值 34 --> 35 lastName:<form:input path="lastName"/><br/> 36 email:<form:input path="email"/><br/> 37 gender:<br/> 38 男:<form:radiobutton path="gender" value="1"/><br/> 39 女:<form:radiobutton path="gender" value="0"/><br/> 40 dept: 41 <!-- 42 items="":指定要遍历的集合 ;自动遍历;遍历出的每一个元素是一个department对象 43 itemLabel="属性名":指定遍历出的这个对象的哪个属性是作为option标签体的值 44 itemValue="属性名":指定刚才遍历出来的这个对象的哪个属性是作为要提交 的value值 45 --> 46 <form:select path="department.id" 47 items="${depts }" 48 itemLabel="departmentName" 49 itemValue="id"></form:select><br/> 50 <input type="submit" value="保存"/> 51 </form:form> 52 53 54 55 56 <!-- (Employee) --> 57 <%-- <form action=""> 58 lastName:<input type="text" name="lastName"/><br/> 59 email:<input type="text" name="email"/><br/> 60 gender: <br/> 61 男:<input type="radio" name="gender" value="1"/><br/> 62 女:<input type="radio" name="gender" value="0"><br/> 63 dept: 64 <select name="department.id"> 65 <c:forEach items="${depts }" var="deptItem"> 66 <!-- 标签体中的是在页面的提示选项信息,value才是真正提交的值 --> 67 <option value="${deptItem.id }">${deptItem.departmentName }</option> 68 </c:forEach> 69 </select> 70 <input type="submit" value="提交"/> 71 </form> --%> 72 </body> 73 </html>
edit.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 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"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 <% 10 pageContext.setAttribute("ctp", request.getContextPath()); 11 %> 12 </head> 13 <body> 14 <h1>员工修改页面</h1> 15 <!-- modelAttribute:这个表单的所有内容显示绑定的是请求域中 employee的值--> 16 <form:form action="${ctp }/emp/${employee.id }" 17 modelAttribute="employee" method="post"> 18 <input type="hidden" name="_method" value="put"/> 19 <input type="hidden" name="id" value="${employee.id }"/> 20 email:<form:input path="email"/><br/> 21 gender: 22 男:<form:radiobutton path="gender" value="1"/> 23 女:<form:radiobutton path="gender" value="0"/><br/> 24 dept: 25 <form:select path="department.id" items="${depts }" 26 itemLabel="departmentName" itemValue="id"></form:select> 27 <br/> 28 <input type="submit" value="修改"/> 29 30 </form:form> 31 </body> 32 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h1>成功!</h1> 11 </body> 12 </html>
jstl的支持,pom.xml:
1 <dependencies> 2 <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl --> 3 <dependency> 4 <groupId>org.apache.taglibs</groupId> 5 <artifactId>taglibs-standard-impl</artifactId> 6 <version>1.2.5</version> 7 </dependency> 8 9 <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec --> 10 <dependency> 11 <groupId>org.apache.taglibs</groupId> 12 <artifactId>taglibs-standard-spec</artifactId> 13 <version>1.2.5</version> 14 </dependency> 15 </dependencies>