今天,在这里总结一下之前写过的一个对员工信息进行增删改查的小项目,首先,先将必要的环境搭建好,员工和部门的实体类以及对应的dao如下
部门实体类:
package com.tanla.springmvc.crud.entities;
public class Department {
private Integer id;
private String departmentName;
public Department() {
// TODO Auto-generated constructor stub
}
public Department(int i, String string) {
this.id = i;
this.departmentName = string;
}
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
+ "]";
}
}
员工实体类:
其中有几个注解
@Past:验证的数据类型 :java.util.Date,java.util.Calendar,Joda Time类库的日期类型
说明 :验证注解的元素值(日期类型)比当前时间早
注解详情参见:http://www.cnblogs.com/easymind223/p/5841043.html
package com.tanla.springmvc.crud.entities;
import java.util.Date;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
public class Employee {
private Integer id;
@NotEmpty
private String lastName;
@Email
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
@Past
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
@NumberFormat(pattern="#,###,###.#")
private Float salary;
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;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department=" + department
+ ", birth=" + birth + ", salary=" + salary + "]";
}
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() {
// TODO Auto-generated constructor stub
}
}
dao层:
package com.tanla.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.tanla.springmvc.crud.entities.Department;
import com.tanla.springmvc.crud.entities.Employee;
@Repository
public class EmployeeDao {
private static Map employees = null;
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap();
employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 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 getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
package com.tanla.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.tanla.springmvc.crud.entities.Department;
@Repository
public class DepartmentDao {
private static Map departments = null;
static{
departments = new HashMap();
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 getDepartments(){
return departments.values();
}
public Department getDepartment(Integer id){
return departments.get(id);
}
}
然后,把Spring mvc的环境搭建好,注意:在web.xml中添加如下拦截器,实现将post请求变成delete或者put请求
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
接下来,说一说这个小项目实现的功能,以及它的流程。
第一步,新建一个index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<a href="emps">Get All Employeea>
body>
html>
第二步,为这个页面的超链接写一个处理方法,新建一个类,名为EmployeeHandler,在里面写一个方法,其中的返回值对应的是一个jsp视图,名为list
@RequestMapping("/emps")
public String list(Map<String, Object> map) {
map.put("employees", employeeDao.getAll());
return "list";
}
第三步,根据Springmvc.xml中的配置信息来创建视图,在本例中,Springmvc.xml是如下配置的,说明所有在EmployeeHandler类中的处理方法返回的视图都在/WEB-INF/views/路径下。所以新建一个list.jsp来显示所有的员工信息
<context:component-scan base-package="com.tanla.springmvc.crud">context:component-scan>
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/">property>
<property name="suffix" value=".jsp">property>
list.jsp:
<c:if test="${empty requestScope.employees }">
没有员工信息
c:if>
<c:if test="${!empty requestScope.employees }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>IDtd>
<td>LAST NAMEtd>
<td>EMAILtd>
<td>GENDERtd>
<td>DEPARTMENTtd>
<td>EDITtd>
<td>DELETEtd>
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}">edita>td>
<td><a class="delete" href="emp/${emp.id}">deletea>td>
tr>
c:forEach>
table>
c:if>
<a href="emp">Add New Employeea>
第四步,写一个添加新员工的功能。,点击list.jsp上面的添加新员工按钮,就会到对应的handler类中的方法中,然后会跳转到input.jsp页面
@RequestMapping(value="/emp" , method = RequestMethod.GET)
public String input(Map maps) {
//将部门信息从数据库中读出来方便表单回显
maps.put("departments",departmentDao.getDepartments() );
//表单显示的时候,域对象里面必须有一个与表单字段对应的bean
maps.put("employee", new Employee());
return "input";
}
input.jsp中应注意事项:
1)action中的路径必须加${pageContext.request.contextPath }
2)页面中的属性必须和实体类中的属性一一对应。
<%@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" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<form:form action="${pageContext.request.contextPath }/emp" method="POST" modelAttribute="employee">
<c:if test="${employee.id == null }">
LastName:<form:input path="lastName" />
c:if>
<c:if test="${employee.id != null }">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT"/>
c:if>
<br><br>
Email:<form:input path="email"/>
<br><br>
<%
MapString > genders = new HashMapString>();
genders.put(1, "male");
genders.put(0, "female");
request.setAttribute("genders",genders);
%>
Gender:<form:radiobuttons path="gender" items="${genders }"/>
<br><br>
Department:<form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id">form:select>
<br><br>
<input type="submit" value="Submit">
form:form>
body>
html>
第五步,点击提交之后,会根据提交方法转到save方法中
@RequestMapping(value="/emp" , method = RequestMethod.POST)
public String save(Employee employee) {
System.out.println(employee);
employeeDao.save(employee);
return "redirect:/emps";
}
第六步,删除操作
list.jsp页面上应该添加如下代码
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var href = $(this).attr("href");
$("form").attr("action",href).submit();
return false;
});
})
script>
为了让静态页面有效果,必须在springmvc.xml配置文件中添加:
<mvc:default-servlet-handler/>
<mvc:annotation-driven>mvc:annotation-driven>
@RequestMapping(value="/emp/{id}",method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
employeeDao.delete(id);
return "redirect:/emps";
}
第七步,修改操作
注意事项:要在handler类中加入如下方法,因为在页面上没有lastName属性,所以不能直接去页面上的值,会导致lastName为空,应该先把数据从数据库中取出来,然后再用页面上的值覆盖它,保证没有修改的值也不会为空。
@ModelAttribute
public void getEmployee(@RequestParam(value="id",required=false)Integer id,
Map maps) {
if(id!=null) {
maps.put("employee", employeeDao.get(id));
}
}
@RequestMapping(value="/emp",method=RequestMethod.PUT)
public String update(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}