用到的包
目录结构,其中只用到了dao、handler和、hello包,只需建立这三个包就OK了
DepartmentDao.java
package cn.springmvc.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import cn.springmvc.hello.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(101,"D-BB"));
departments.put(103,new Department(101,"D-CC"));
departments.put(104,new Department(101,"D-DD"));
departments.put(105,new Department(101,"D-EE"));
}
public Collection<Department> getDepartments(){
return departments.values();
}
public Department getDepartment(Integer id){
return departments.get(id);
}
}
EmployeeDao.java
package cn.springmvc.dao;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cn.springmvc.hello.Department;
import cn.springmvc.hello.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"),new Date()));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB"),new Date()));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC"),new Date()));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD"),new Date()));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE"),new Date()));
}
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 void delete(Integer id){
employees.remove(id);
}
public Collection<Employee> getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
}
EmployeeHandler.java
package cn.springmvc.handler;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import cn.springmvc.dao.DepartmentDao;
import cn.springmvc.dao.EmployeeDao;
import cn.springmvc.hello.Department;
import cn.springmvc.hello.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
//@InitBinder
//public void initBinder(WebDataBinder webBinder){
// webBinder.setAllowedFields("lastName");
//}
//修改操作
@RequestMapping(value="/emp",method=RequestMethod.PUT)
public String update(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
@ModelAttribute
public void getEmployee(@RequestParam(value="id",required=false) Integer id,
Map<String,Object> map){
if(id!=null){
map.put("employee", employeeDao.get(id));
}
}
//以下做的是回显的操作,也就是在list页面点击edit后可以跳转到input页面,并且回显所点击的
//行的数据
@RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
public String input(@PathVariable("id") Integer id,Map<String,Object>map){
map.put("employee", employeeDao.get(id));//键值employee必须和input页面中的modelAttribute的值一致
map.put("departments", departmentDao.getDepartments());
return "input";
}
@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable("id")Integer id){
employeeDao.delete(id);
//返回根目录下的emps
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());则添加一个空的employee,以下的写法不是空的
map.put("employee",new Employee());
return "input";
}
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String save(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
@RequestMapping("/emps")
public String list(Map<String,Object> map){
map.put("employees",employeeDao.getAll());
return "list";
}
}
Department.java
package cn.springmvc.hello;
public class Department {
private Integer id;
private String departmentName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName="
+ departmentName + "]";
}
public Department(Integer id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
public Department() {
super();
}
}
Employee.java
package cn.springmvc.hello;
import java.util.Date;
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
private Department department;
private Date birth;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department="
+ department + ", birth=" + birth + "]";
}
public Employee(Integer id, String lastName, String email,
Integer gender, Department department, Date birth) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
this.birth = birth;
}
public Employee(Integer id, String lastName, String email,
Integer gender, Department department) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
}
public Employee() {
super();
}
}
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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="cn.springmvc"></context:component-scan>
<!-- 配置视图解析器,如何把handler方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 导入jquery包和其他样式时不拦截需要以下配置,不拦截静态资源 -->
<mvc:default-servlet-handler/>
<!-- 配置mvc注解驱动 -->
<!-- 例如@resquestmapping这类的 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
inpue.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<%@page import="java.util.Map" %>
<%@page import="java.util.HashMap" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%-- 以上是sringmvc的表达标签 --%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br><br>
<!-- 使用form标签可以快速开发表单页面,可以方便的完成表单值回显 -->
<!-- modelAttribute="employee"中的属性值与handler中的map.put("employee",new Employee());一致 -->
<form:form action="${pageContext.request.contextPath }/emp" method="POST" modelAttribute="employee">
<!-- path属性对应html表单标签的name属性值 -->
<c:if test="${employee.id==null }">
LastName:<form:input path="lastName"/>
</c:if>
<c:if test="${employee.id!=null }">
<form:hidden path="id"/>
<!--path所对应的属性必须在modelAttribute的bean中存在对应的属性,也就是
以上的modelAttribute="employee",所以以下的input不能用form:input
来写,对于—_method不能使用form:hidden标签,因为modelAttribute对应的bean中没有_method
这个属性 ,应该用<input type="hidden" name="_method" value="PUT"/>-->
<!-- 把post转为put请求,用以下隐藏域方法来转换 -->
<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}"></form:radiobuttons>
<br>
Department:<form:select path="department.id" items="${departments}" itemLabel="departmentName" itemValue="id">
</form:select>
<br>
<!--
1、数据类型转换
2、数据类型格式化
3、数据校验
-->
Birth:<form:input path="birth"/>
<input type="submit" value="everything"/>
</form:form>
</body>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%-- <%@ page contentType="text/html;charset=UTF-8" language="java" %> --%>
<%-- <%@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=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
alert("kaixin");
})
<%--确定jquery包已经导入 --%>
</script>
<%-- 以下是删除相关的代码 --%>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var href=$(this).attr("href");
$("form").attr("action",href).submit();
return false;
});
})
</script>
<%-- 以上是删除相关的代码 --%>
</head>
<body>
<!-- 以下是删除name="_method"为固定写法,Method从Post方法转为Delete请求 -->
<form action="" method="POST">
<input type="hidden" name="_method" value="DELETE"/>
</form>
<!-- 以上是删除 -->
<c:if test="${empty requestScope.employees}">
没有任何员工信息
</c:if>
<c:if test="${not empty requestScope.employees}">
<table border="1" cellpadding="10" cellspacing="10">
<tr>
<td>ID</td>
<td>LastName</td>
<td>Email</td>
<td>Gender</td>
<td>Department</td>
<td>Edit</td>
<td>Delete</td>
</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>
<a href="emp">add new employee</a>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- 配置org.springframework.web.filter.HiddenHttpMethodFilter:可以把POST请求转为
delete或put请求-->
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置DispatcherServlet的一个初始化参数:配置SpringMVC配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置:把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>
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="emps">List All Employees</a>
</body>
</html>
ok了