SpringMVC
RESTRUL_CRUD_需求
-
向EmployeeHandle.java中写入一个方法
-
package com.atguigu.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.atguigu.springmvc.crud.dao.DepartmentDao; import com.atguigu.springmvc.crud.dao.EmployeeDao; import com.atguigu.springmvc.crud.entities.Department; import com.atguigu.springmvc.crud.entities.Employee; @Controller public class EmployeeHandle { @Autowired private EmployeeDao employeeDao; @Autowired //注意这个AutoWired必须要加 否则就会报错 private DepartmentDao departmentDao; @RequestMapping("/emps") public String list(Map<String,Object> map) { map.put("employees", employeeDao.getAll()); return "list"; } }
-
-
配置springmvc.xml文件
-
<!-- 配置自动扫描的包 --> <context:component-scan base-package="com.atguigu.springmvc"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
-
-
在web.xml文件中加入如下配置
-
<!-- 配置 SpringMVC 的 DispatcherServlet --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
-
-
index.jsp 进入页面
<a href="emps">List All Employees</a>
-
list.jsp显示页面
-
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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> <c:if test="${empty requestScope.employees }"> 没有任何员工信息. </c:if> <c:if test="${!empty requestScope.employees }"> <table border="1" cellpadding="10" cellspacing="0"> <tr> <th>ID</th> <th>LastName</th> <th>Email</th> <th>Gender</th> <th>Department</th> <th>Edit</th> <th>Delete</th> </tr> <c:forEach items="${requestScope.employees }" var="emp"> <tr> <td>${emp.id }</td> <td>${emp.lastName }</td> <td>${emp.email }</td> <td>${emp.gender == 0 ? 'Female' : 'Male' }</td> <td>${emp.department.departmentName }</td> <td><a href="">Edit</a></td> <td><a href="emp/${emp.id}">Delete</a></td> </tr> </c:forEach> </table> </c:if> <br><br> <a href="emp">Add New Employee</a>
-
-
最后检索出如上图所示页面
-
向EmployeeHandle.java添加两个方法
-
@RequestMapping(value="/emp",method=RequestMethod.POST) public String save(Employee employee) { employeeDao.save(employee); return "redirect:/emps"; } //这是一个get请求 @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"; }
-
-
添加input.jsp页面
-
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@page import="java.util.HashMap"%> <%@page import="java.util.Map"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- 1. WHY 使用 form 标签呢 ? 可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显 2. 注意: 可以通过 modelAttribute 属性指定绑定的模型属性, 若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean 如果该属性值也不存在,则会发生错误。 --> <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); %> Gender: <br> <form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/> <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>
-
-
删除操作
-
先向EmployeeHandle.java添加一个方法
-
@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE) public String delete(@PathVariable("id") Integer id) { employeeDao.delete(id); return "redirect:/emps"; }
-
-
再向list.jsp中添加如下代码
-
<!-- SpringMVC 处理静态资源: 1. 为什么会有这样的问题: 优雅的 REST 风格的资源URL 不希望带 .html 或 .do 等后缀 若将 DispatcherServlet 请求映射配置为 /, 则 Spring MVC 将捕获 WEB 容器的所有请求, 包括静态资源的请求, SpringMVC 会将他们当成一个普通请求处理, 因找不到对应处理器将导致错误。 2. 解决: 在 SpringMVC 的配置文件中配置 <mvc:default-servlet-handler/> --> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(function(){ $(".delete").click(function(){ var href = $(this).attr("href"); $("form").attr("action", href).submit(); return false; }); }) </script>
<form action="" method="POST"> <input type="hidden" name="_method" value="DELETE"/> </form> <td><a class="delete" href="emp/${emp.id}">Delete</a></td> <!--还有这里也要添加-->
-
-
在springmvc.xml中加入如下代码
-
<!-- default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler, 它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理 一般 WEB 应用服务器默认的 Servlet 的名称都是 default. 若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 --> <mvc:default-servlet-handler/> <mvc:annotation-driven></mvc:annotation-driven>
-
-
-
修改操作
-
显示修改页面
-
EmployeeHandle.java添加一个方法
-
@RequestMapping(value="/emp/{id}",method=RequestMethod.GET) public String input(@PathVariable("id") Integer id,Map<String,Object> map) { map.put("employee",employeeDao.get(id)); map.put("departments",departmentDao.getDepartments()); return "input"; }
-
-
-
修改员工信息
-
EmployeeHandle.java添加两个方法
-
@ModelAttribute public void getEmployee(@RequestParam(value="id",required = false) Integer id, Map<String,Object> map) { if(id!=null) { map.put("employee", employeeDao.get(id)); } } @RequestMapping(value="/emp",method=RequestMethod.PUT) public String update(Employee employee) { employeeDao.save(employee); return "redirect:/emps"; }
-
-
-
修改input.jsp中信息,增加了c:if
-
<!-- 这里的action变成绝对路径了 以后都建议使用绝对路径 --> <form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee"> <c:if test="${employee.id ==null }"> <!-- path属性对应html表单标签的name属性值 --> LastName:<form:input path="lastName"/> </c:if> <c:if test="${employee.id !=null }"> <form:hidden path="id"/> <input type="hidden" name="_method" value="PUT"/> <%-- 对于 _method 不能使用 form:hidden 标签, 因为 modelAttribute 对应的 bean 中 没有 _method 这个属性 --%> <%-- <form:hidden path="_method" value="PUT"/> --%> </c:if> <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); %> Gender: <br> <form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/> <br> Department: <form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id"></form:select> <br> <input type="submit" value="Submit"/> </form:form>
-
修改list.jsp中的超链接
<td><a href="emp/${emp.id}">Edit</a></td>
-
-
-
相关的类
-
com.atguigu.springmvc.crud.dao
-
DepartmentDao.java
package com.atguigu.springmvc.crud.dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Repository; import com.atguigu.springmvc.crud.entities.Department; @Repository public class DepartmentDao { private static Map<Integer, Department> departments = null; static{ departments = new HashMap<Integer, Department>(); departments.put(101, new Department(101, "D-AA")); departments.put(102, new Department(102, "D-BB")); departments.put(103, new Department(103, "D-CC")); departments.put(104, new Department(104, "D-DD")); departments.put(105, new Department(105, "D-EE")); } public Collection<Department> getDepartments(){ return departments.values(); } public Department getDepartment(Integer id){ return departments.get(id); } }
-
EmployeeDao.java
package com.atguigu.springmvc.crud.dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.atguigu.springmvc.crud.entities.Department; import com.atguigu.springmvc.crud.entities.Employee; @Repository public class EmployeeDao { private static Map<Integer, Employee> employees = null; @Autowired private DepartmentDao departmentDao; static{ employees = new HashMap<Integer, Employee>(); employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA"))); employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB"))); employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC"))); employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD"))); employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE"))); } private static Integer initId = 1006; public void save(Employee employee){ if(employee.getId() == null){ employee.setId(initId++); } employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId())); employees.put(employee.getId(), employee); } public Collection<Employee> getAll(){ return employees.values(); } public Employee get(Integer id){ return employees.get(id); } public void delete(Integer id){ employees.remove(id); } }
-
-
com.atguigu.springmvc.crud.entities
-
Department.java 里面有私有属性id departmentName 带参,不带参的构造器还有toString()方法
-
Employee.java 里面有私有属性id,lastName,email,gender,department 相关的构造器和toString()方法
-
-
使用Spring的表单标签
-
WHY 使用 form 标签呢 ?
可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显 -
<!-- 1. WHY 使用 form 标签呢 ? 可以更快速的开发出表单页面, 而且可以更方便的进行表单值的回显 2. 注意: 可以通过 modelAttribute 属性指定绑定的模型属性, 若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean 如果该属性值也不存在,则会发生错误。 --> <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); %> Gender: <br> <form:radiobuttons path="gender" items="${genders}" delimiter="<br>"/> <br> Department: <form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id"></form:select> <br> <input type="submit" value="Submit"/> </form:form>
*