学习SpringMVC(十五)之CRUD操作
Posted 奔跑着的国风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习SpringMVC(十五)之CRUD操作相关的知识,希望对你有一定的参考价值。
使用SpringMVC完成相应的CRUD操作,静态数据来模仿从数据库中取数据。
下面从创建的类说起,一共定义了5个类,分类是DepartmentDao,EmployeeDao,Department,Employee,EmployeeHandler
代码如下:
package com.cgf.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.cgf.springmvc.crud.entities.Department; import com.cgf.springmvc.crud.entities.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", "[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<Employee> getAll(){ return employees.values(); } public Employee get(Integer id){ return employees.get(id); } public void delete(Integer id){ employees.remove(id); } }
package com.cgf.springmvc.crud.dao; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Repository; import com.cgf.springmvc.crud.entities.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); } }
package com.cgf.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 + "]"; } }
package com.cgf.springmvc.crud.entities; import java.util.Date; import javax.validation.constraints.NotNull; 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; @NotNull private String lastName; @Email private String email; //1 male, 0 female private Integer gender; private Department department; @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 } }
package com.cgf.springmvc.crud.handlers; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.cgf.springmvc.crud.dao.DepartmentDao; import com.cgf.springmvc.crud.dao.EmployeeDao; import com.cgf.springmvc.crud.entities.Employee; @RequestMapping(value="/springmvc") @Controller public class EmployeeHandler { @Autowired private EmployeeDao employeeDao; @Autowired private DepartmentDao departmentDao; @RequestMapping(value="/list") public String emps(Map<String,Object> map){ map.put("emplists", employeeDao.getAll()); return "list"; } @RequestMapping(value="/addUi",method=RequestMethod.GET) public String empsAddUI(Map<String,Object> map){ map.put("department", departmentDao.getDepartments()); map.put("employee", new Employee()); return "input"; } @RequestMapping(value="/add",method=RequestMethod.POST) public String empsAdd(Employee employee,Map<String,Object> map){ employeeDao.save(employee); //map.put("emplists", employeeDao.getAll()); return "redirect:list"; } @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE) public String empsDelete(@PathVariable("id")Integer id,Map<String,Object> map){ employeeDao.delete(id); map.put("emplists", employeeDao.getAll()); return "list"; } @RequestMapping(value="/EditUi/{id}",method=RequestMethod.GET) public String empsEditUI(@PathVariable("id")Integer id,Map<String,Object> map){ map.put("department", departmentDao.getDepartments()); map.put("employee", employeeDao.get(id)); return "input"; } @ModelAttribute public void emps(@RequestParam(value="id",required=false)Integer id,Map<String,Object> map){ if(id!=null){ map.put("employee", employeeDao.get(id)); } } @RequestMapping(value="/add",method=RequestMethod.PUT) public String empsEdit(Employee employee,Map<String,Object> map){ employeeDao.save(employee); map.put("emplists", employeeDao.getAll()); return "list"; } }在index.jsp中:首页用来显示所有的员工,是个GET请求
<h2>SpringMVC CRUD</h2> <a href="springmvc/list">显示所有员工信息</a>在input.jsp中;该页面有两个用处,一个是对添加员工进行操作(post请求),另一个用来对员工信息的修改(put请求)
<form:form action="springmvc/add" method="POST" modelAttribute="employee"> <c:if test="${employee.id==null }"> LastName:<form:input path="lastName"/> <br> </c:if> <c:if test="${employee.id!=null }"> <form:hidden path="id"/> <input type="hidden" name="_method" value="PUT"> </c:if> Email:<form:input path="email"/> <form:errors path="email"></form:errors><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 }"/><br> Department:<form:select path="department.id" items="${department}" itemLabel="departmentName" itemValue="id"></form:select> <input type="submit" value="Submit" /> </form:form>在list.jsp中:显示所有员工信息,在DELETE操作中,将GET请求,通过JQUERY完成转化为DELETE请求
<span style="font-family:SimSun;"><span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'list.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(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 requestScope.emplists }"> 没有任何员工信息 </c:if> <c:if test="${!empty requestScope.emplists }"> <table border="1"> <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.emplists}" var="emps"> <tr> <td>${emps.id }</td> <td>${emps.lastName}</td> <td>${emps.email }</td> <td>${emps.gender==0 ? 'Female':'male'}</td> <td>${emps.department.departmentName }</td> <td><a href="springmvc/EditUi/${emps.id}">Edit</a></td> <td><a class="delete" href="springmvc/delete/${emps.id}">Delete</a></td> </tr> </c:forEach> </table> </c:if> <a href="springmvc/addUi">添加员工信息</a> </body> </html></span> </span>注意:
对静态资源的处理,需要在spring.xml文件中配置<mvc:default-servlet-handler/>default-servlet-handler将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,它会对进入DispatcherServlet的请求进行筛查, 如果发现是没有经过映射的请求,
就将该请求交由WEB应用服务器默认的Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理
以上是关于学习SpringMVC(十五)之CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章
学习笔记——@PathVariable注解基本使用;@PathVariable注解属性;REST风格CRUD概述;实现PUT&DELETE提交方法步骤;SpringMVC处理请求数据请求头处理
[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作
第121天学习打卡(MyBatisPlus CRUD扩展之查询操作 分页查询 删除操作 逻辑删除 条件构造器 自动生成器 )