需求:在首页点击链接显示全部employee信息,点击edit和delete分别进行修改和删除操作,点击add进行添加操作。CRUD分别对应post get put delete四种请求。
目录结构如图
web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 配置 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> </web-app>
springmvc.xml配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com"></context:component-scan><!-- <bean id="HelloWorldController" class="com.springmvc.handlers.EmployeeHandler" /> --> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler, 它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理 一般 WEB 应用服务器默认的 Servlet 的名称都是 default. 若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 --> <mvc:default-servlet-handler /> <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionAttribute" value="ex"></property> <property name="exceptionMappings"> <props> <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop> </props> </property> </bean> </beans>
Department.java
public class Department { private Integer id; private String departmentName; //... }
Employee.java
public class Employee { private Integer id; private String lastName; private String email; private Integer gender; //1 male 0 female private Department department; //... }
-----------------------------------------------------------------------
DepartmenDao.java
@Repository public class DepartmenDao { //模拟数据库操作 private static Map<Integer, Department> departments = null; static{ departments = new HashMap<Integer, Department>(); departments.put(1, new Department(1, "D-AA1")); departments.put(2, new Department(2, "D-AA2")); departments.put(3, new Department(3, "D-AA3")); departments.put(4, new Department(4, "D-AA4")); departments.put(5, new Department(5, "D-AA5")); } public Collection<Department> getDepartments(){ return departments.values(); } public Department getDepartment(Integer id) { return departments.get(id); } }
EmployeeDao.java
@Repository public class EmployeeDao { //模拟数据库操作 private static Map<Integer, Employee> employees = null; @Autowired private DepartmenDao departmenDao; static{ employees = new HashMap<Integer, Employee>(); employees.put(1, new Employee(1, "E-AA1", "1@126.com", 0, new Department(1,"D-AA1"))); employees.put(2, new Employee(2, "E-AA2", "2@126.com", 1, new Department(1,"D-AA1"))); employees.put(3, new Employee(3, "E-AA3", "3@126.com", 0, new Department(2,"D-AA2"))); employees.put(4, new Employee(4, "E-AA4", "4@126.com", 0, new Department(3,"D-AA3"))); employees.put(5, new Employee(5, "E-AA5", "5@126.com", 1, new Department(1,"D-AA1"))); } private static Integer initId = 1; public void save(Employee employee) { if (employee.getId() == null) {//insert or update employee.setId(initId++); } employee.setDepartment(departmenDao.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); } }
EmployeeHandler.java 处理http请求
@Controller public class EmployeeHandler { @Autowired private EmployeeDao employeeDao; @Autowired private DepartmenDao departmenDao; @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("/emps") //对应index.jsp的链接请求 public String list(Map<String, Object>map) { // System.out.println(employeeDao.getAll()); map.put("employees", employeeDao.getAll()); return "list";//list.jsp } //add操作 @RequestMapping(value="/emp", method=RequestMethod.GET) public String input(Map<String, Object> map) { map.put("departments", departmenDao.getDepartments()); //默认要进行表单回显,所以这里要放一个employee到map里面, //对应input.jsp中的modelAttribute="employee" map.put("employee", new Employee());//input.jsp line17 return "input"; } @RequestMapping(value="/emp", method=RequestMethod.POST) public String save(Employee employee) { employeeDao.save(employee); return "redirect:/emps"; } @RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE) public String delete(@PathVariable("id") Integer id) { employeeDao.delete(id); return "redirect:/emps"; } //与前面add操作的input方法不同,此处需要接收参数 @RequestMapping(value="/emp/{id}", method=RequestMethod.GET) public String input(@PathVariable("id") Integer id, Map<String, Object> map) { //默认要进行表单回显,所以这里要放一个employee到map里面, //对应input.jsp中的modelAttribute="employee" map.put("employee", employeeDao.get(id)); map.put("departments", departmenDao.getDepartments()); return "input"; } @RequestMapping(value="/emp", method=RequestMethod.PUT) public String update(Employee employee) { employeeDao.save(employee); return "redirect:/emps"; } }
index.jsp
<a href="emps">List all employees</a><!-- 跳转到list.jsp -->
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!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"> <script type="text/javascript" src="js/jquery-1.9.0.min.js"></script> <!-- SpringMVC处理静态资源 优雅的REST风格的资源URL不希望带.html .do等后缀 若将DispatcherServerlet请求映射配置为/,则SpringMVC将捕获web容器的所有请求, SpringMVC会将获取js的资源请求也当做普通请求拦截,则因找不到对应处理器而发生错误。 解决办法:在SpringMVC的配置文件中配置<mvc:default-servlet-handler /> --> <script type="text/javascript"> $(function() { $(".delete").click(function() { //将post请求转为delete请求 var href = $(this).attr("href"); $("form").attr("action", href).submit(); return false; }); }) </script> <title>Insert title here</title> </head> <body> <form action="" method="post"> <input type="hidden" name="_method" value="DELETE" /> </form> <c:if test="${empty requestScope.employees}"> 没有员工信息 </c:if> <c:if test="${!empty requestScope.employees}"> <table border="1" cellspacing="0" cellpadding="10"> <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="emp/${emp.id}">Edit</a></td> <td><a class="delete" href="emp/${emp.id}">Delete</a></td> </tr> </c:forEach> </table> </c:if> <br /> <a href="emp">Add new emp</a> </body> </html>
<a href="emp">Add new emp</a> 链接到input页面
input.jsp 添加和修改公用
<%@page import="java.util.HashMap"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.HashMap"%> <%@ page import="java.util.Map"%> <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!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> <!-- 使用SpringMVC表单标签,可以进行表单回显 可以通过ModelAttribute属性指定绑定的模型属性。 若没有指定该属性,则默认从request域对象中读取command的表单bean 若该属性值也不存在,则会发生错误。 --> <!-- modelAttribute="employee" 与EmployeeHandler.java line26一值。 SpringMVC默认要进行表单回显。 --> <!-- 开发的时候推荐使用绝对路径 --> <form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee"> <!-- 不允许修改用户的LastName,当id不为空的时候即为修改操作 --> <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" /> <!-- 修改操作发送PUT请求,这里不能用form:hidden标签,因为modelAttribute对应的bean里没有_method属性 --> <input type="hidden" name="_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<form:radiobuttons path="gender" items="${genders}" delimiter="<br/>" /> <!-- delimiter换行 --> <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>
删除请求对应handler中的delete请求
项目源码地址 http://yunpan.cn/cZGr5gD94z3xI 访问密码 8069