Rest风格的CRUD
首先定义javaBean也就是Model
//Department.java
package com.niu.bean;
import org.springframework.stereotype.Component;
@Component
public class Department {
private Integer id;
private String departmentName;
public Department() {
}
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 + "]";
}
}
//Employee.java
package com.niu.bean;
import java.util.Date;
import org.springframework.stereotype.Component;
@Component
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
public Employee() {
super();
}
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 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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department=" + department
+ "]";
}
}
step2
定义dao层
//DepartmentDao.java
package com.niu.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.niu.bean.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
package com.niu.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.niu.bean.Department;
import com.niu.bean.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);
}
}
step3:
接下来是控制层
package com.niu.controller;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
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 com.niu.bean.Department;
import com.niu.bean.Employee;
import com.niu.dao.DepartmentDao;
import com.niu.dao.EmployeeDao;
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@Autowired
DepartmentDao departmentDao;
@RequestMapping("/emps")
public String getEmps(Model model){
Collection<Employee> all = employeeDao.getAll();
model.addAttribute("emps", all);
System.out.println("显示所有的员工....");
return "list";
}
/**
* 添加
* @param employee
* @return
*/
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String addEmp(Employee employee){
System.out.println(employee);
employeeDao.save(employee);
return "redirect:/emps";
}
/**
* 查询指定的员工
* @param id
* @param model
* @return
*/
@RequestMapping(value="emp/{id}",method=RequestMethod.GET)
public String getEmp(@PathVariable("id")Integer id,Model model){
Employee employee = employeeDao.get(id);
model.addAttribute("employee", employee);
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
return "edit";
}
@RequestMapping(value="/emp/{id}",method=RequestMethod.PUT)
public String updateEmp(Employee employee,@PathVariable("id")Integer id){
System.out.println("要修改的员工:"+employee);
employeeDao.save(employee);
return "redirect:/emps";
}
/**
* 跳转到添加的页面
* @param model
* @return
*/
@RequestMapping("/toaddpage")
public String toAddpage(Model model){
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts", departments);
model.addAttribute("employee",new Employee(null, "yy", "2691778746@qq.com", 0,departmentDao.getDepartment(101)));
return "add";
}
/**
* 删除
*/
@RequestMapping("/emp/{id}")
public String delEmp(@PathVariable("id")Integer id){
Employee employee = employeeDao.get(id);
System.out.println("要删除的员工是:"+employee);
employeeDao.delete(id);
return "redirect:/emps";
}
/**
* 提前查询,每一个方法运行之前他都会提前运行
* @param id
* @param model
*/
@ModelAttribute
public void myModelAttribute(@RequestParam(value="id",required=false)Integer id,Model model){
if(id!=null){
Employee employee = employeeDao.get(id);
model.addAttribute("employee",employee);
}
System.out.println("hah ");
}
}
step4:
接下来是前台页面
index页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<a href="hello">hello</a>
<jsp:forward page="/emps"></jsp:forward>
</body>
</html>
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>员工列表</title>
<%
pageContext.setAttribute("ctp",request.getContextPath());
%>
<script type="text/javascript" src="${ctp}/jquery-1.9.1.min.js">
</script>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>ID</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>departmentName</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
<c:forEach items="${emps}" var="emp">
<tr>
<td>${emp.id}</td>
<td>${emp.lastName}</td>
<td>${emp.email}</td>
<td>${emp.gender==0?"女":"男"}</td>
<td>${emp.department.departmentName}</td>
<td>
<a href="${ctp}/emp/${emp.id}">EDIT</a>
</td>
<td>
<a href="${ctp}/emp/${emp.id}" class="delBtn">DELETE</a>
</td>
</tr>
</c:forEach>
</table>
<a href="${ctp}/toaddpage">添加员工</a>
<form id="deleteForm" action="${ctp}/emp/${emp.id}" method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="删除">
</form>
<script type="text/javascript">
$(function(){
$(".delBtn").click(function(){
$("#deleteForm").attr("action",this.href);
$("#deleteForm").submit();
return false;
});
})
</script>
</body>
</html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>员工添加页面</title>
</head>
<body>
<h1>添加员工</h1>
<!--
SpringMVC认为,表单中的每一项数据都是需要进行回显的
path:指定的是一个属性:这个属性是从隐含模型(请求域中 取出的某个对象中的属性)
-->
<!--
1.modelAttribute="" 以前我们的表单会从请求域中获取一个command对象,把这个对中的每一个属性对应的显示在页面上
2.告诉SpringMVC不要去取command的值了我放了一个modelAttribute的值、取对象用的key就用我modelAttribute指定的
-->
<%pageContext.setAttribute("ctp",request.getContextPath()); %>
<form:form action="${ctp}/emp" modelAttribute="employee" method="post">
<!--
path
当作原生的name属性
自动回显隐含模型中的某个对象对应的这个属性值
-->
lastName:<form:input path="lastName"/><br>
email:<form:input path="email"/><br>
gender:<br>
男:<form:radiobutton path="gender" value="1"/><br>
女:<form:radiobutton path="gender" value="0"/><br>
dept:<br>
<!--
items="":指定要遍历的集合,自动遍历,遍历出的每一个元素是一个department对象
itemLabel="属性":指定遍历出的这个对象的那个属性是作为option标签体的值
itemValue="":指定刚才遍历出来的这个对象的那个属性是作为要提交的value值
-->
<form:select path="department.id" items="${depts}" itemLabel="departmentName" itemValue="id">
</form:select>
<input type="submit" value="提交">
</form:form>
<!--
<form action="">
lastName:<input type="text" name="lastName"><br>
email:<input type="text" name="email"><br>
gender:
男:<input type="radio" name="gender" value="1"><br>
女:<input type="radio" name="gender" value="0"><br>
dept:<select name="department.id">
<c:forEach items="${depts}" var="deptItem">
<option value="${deptItem.id}">${deptItem.departmentName}</option>
</c:forEach>
</select>
</form>
-->
</body>
</html>
edit页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>
<h1>修改员工</h1>
<%pageContext.setAttribute("ctp",request.getContextPath());%>
<!--
modelAttribute 这个表单的所有内容显示绑定的是请求域中的employee的值
-->
<form:form action="${ctp}/emp/${employee.id}" modelAttribute="employee" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="id" value="${employee.id}">
lastName:<form:input path="lastName"/><br>
email:<form:input path="email"/><br>
gender:<br>
男:<form:radiobutton path="gender" value="1"/><br>
女:<form:radiobutton path="gender" value="0"/><br>
dept:<br>
<form:select path="department.id" items="${depts}" itemLabel="departmentName" itemValue="id">
</form:select>
<input type="submit" value="提交">
</form:form>
</body>
</html>
接下来完成测试即可