七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查

RESTful SpringMVC CRUD

相关的类:

  • 实体类:Employee、Department
  • – Handler:EmployeeHandler
  • – Dao:EmployeeDao、DepartmentDao

相关的页面:

  • index.jsp
  • form.jsp
  • list.jsp

共同代码:
EmployeeDao:

package com.abc.springmvc.crud.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.abc.springmvc.crud.entities.Department;
import com.abc.springmvc.crud.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;



@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, "花城", "[email protected]", 1, new Department(101, "鬼王")));
		employees.put(1002, new Employee(1002, "白凤", "[email protected]", 1, new Department(102, "刺客")));
		employees.put(1003, new Employee(1003, "项羽", "[email protected]", 0, new Department(103, "坦克")));
		employees.put(1004, new Employee(1004, "虞姬", "[email protected]", 0, new Department(104, "射手")));
		employees.put(1005, new Employee(1005, "卫庄", "[email protected]", 1, new Department(105, "坦克")));
	}
	
	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);
	}
}

DepartmentDao:

package com.abc.springmvc.crud.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.abc.springmvc.crud.entities.Department;
import org.springframework.stereotype.Repository;


@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);
	}
	
}

Employee:

package com.abc.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
	}
}

epartment:

package com.abc.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
				+ "]";
	}
	
}

1.显示所有员工信息

-URL:emps
-请求方式:GET
-显示效果

七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查_第1张图片

实现代码:
Controller:

 @Autowired
    private EmployeeDao employeeDao;

    @RequestMapping("/emps")
    public String getList(Map<String,Object> map){
        map.put("employees",employeeDao.getAll());
        return "list";
    }

2.添加操作

-显示添加页面:
	. 	URI:emp
	.请求方式:GET
-添加员工信息:
	.URI:EMP
	请求方式:POST
	显示效果:完成添加,重定向到list页面

七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查_第2张图片
七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查_第3张图片
实现代码:
添加页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="for" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <form:form action="emp" method="post" modelAttribute="employee">
        LastName: <form:input path="lastName">form:input><br>
        Email:<form:input path="email">form:input><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:<for:select path="department.id" items="${departments}" itemLabel="departmentName" itemValue="id">for:select>
        <br>
        <input type="submit" name="Submit">
    form:form>
body>
html>

注:
1.这里使用了form标签,之所以使用form标签是因为这样可以更加快速的开发出表单页面,而且可以更方便的进行表单值得回显。
2.可以通过modelAttribute属性指定绑定的模型属性,若没有指定该属性,则默认从request域对象中读取command的表单bean,如果该属性值也不存在,则会发生错误。

删除操作

-显示添加页面:
	-URI:emp/{id}
	-请求方式:DELETE
	-删除后效果:对应记录从数据表中删除。

删除操作的请求方式为DELETE所以我们需要进行转换,在list页面添加一个form标签,里面加入,
使用js方式将Post请求转为DELETE请求:
list.jsp页面代码:

<html>
<head>
    <title>Titletitle>
    <script type="text/javascript" src="./scripts/jquery-1.9.1.min.js">script>
    <script>
        $(function(){
            $(".delete").click(function(){
                var href = $(this).attr("href");
                $("form").attr("action", href).submit();
                return false;
            });
        });
    script>
head>
<body>

<form action="" method="POST">
    <input type="hidden" name="_method" value="DELETE"/>
form>
    <c:if test="${empty employees}">
        还没有员工信息
    c:if>

    <c:if test="${not empty employees}">
        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>IDth>
                <th>LastNameth>
                <th>Emailth>
                <th>Genderth>
                <th>Departmentth>
                <th>Editth>
                <th>Deleteth>
            tr>
            <c:forEach items="${employees}" var="emp">
                <tr>
                    <td>${emp.id}td>
                    <td>${emp.lastName}td>
                    <td>${emp.email}td>
                    <td>${emp.gender==1?'Male':'Female'}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>
    <br><br>
    <a href="emp">Add Employeea>

body>

Controller层处理删除请求代码:

 @RequestMapping(value = "/emp/{id}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id") int id){
        employeeDao.delete(id);
        return "redirect:/emps";
    }

修改操作

-显示修改页面:
	- URI:emp/{id}
	- 请求方式:GET
	- 显示效果:回显表单。
-修改员工信息:
	- URI:emp
	- 请求方式:PUT
	- 员工的lastName属性不可修改
	- 回显效果:完成修改,重定向到list页面。

显示修改页面和添加页面为同一个页面:form.jsp,但需要稍作修改,代码如下:
 <form:form action="${pageContext.request.contextPath }/emp"  method="post" modelAttribute="employee">
       <c:if test="${employee.id==null}">
           
           LastName: <form:input path="lastName">form:input><br>
       c:if>
        <c:if test="${employee.id!=null}">
            
            <form:hidden path="id">form:hidden>
            <%-- 对于 _method 不能使用 form:hidden 标签, 因为 modelAttribute 对应的 bean 中没有 _method 这个属性 --%>
            <input type="hidden" name="_method" value="PUT">
        c:if>
        Email:<form:input path="email">form:input><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:<for:select path="department.id" items="${departments}" itemLabel="departmentName" itemValue="id">for:select>
        <br>
        <input type="submit" name="Submit">
    form:form>

其中,需要将post请求转为PUT请求,该实现方法在前面的文章已做了说明。
controller层的请求跳转到显示修改页面代码:

 @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    public String editEmployee(@PathVariable("id") int id,Map<String,Object> map){
        map.put("employee",employeeDao.get(id));
        map.put("departments",departmentDao.getDepartments());
        return "form";
    }

保存修改内容代码:

@RequestMapping(value = "/emp",method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/emps";
    }

以上完成了员工信息的修改,效果图如下:
七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查_第4张图片
七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查_第5张图片
从以上结果可以看出,当保存修改后,lastName属性丢失了,这时,我们只需要在controller中加入以下方法:

   @ModelAttribute
    public void getEmployee(@RequestParam(value="id",required=false) Integer id,
                            Map<String, Object> map){
        if(id != null){
            map.put("employee", employeeDao.get(id));
        }
    }

在方法被@ModelAttribute标记,在执行controller中的方法时,会最先调用该方法。加入之后实现效果如下:
七、SpringMVC--RESTful SpringMVC CRUD---实现员工信息增删改查_第6张图片

你可能感兴趣的:(SpringMVC,springmvc)