admin管理员组

文章数量:1794759

Spring MVC (6) spring MVC 写一个增删改查的小项目

Spring MVC (6) spring MVC 写一个增删改查的小项目

今天,在这里总结一下之前写过的一个对员工信进行增删改查的小项目,首先,先将必要的环境搭建好,员工和部门的实体类以及对应的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类库的日期类型 说明 :验证注解的元素值(日期类型)比当前时间早 注解详情参见:wwwblogs/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<Integer, Employee> employees = null; @Autowired private DepartmentDao departmentDao; static{ employees = new HashMap<Integer, Employee>(); employees.put(1001, new Employee(1001, "E-AA", "aa@163", 1, new Department(101, "D-AA"))); employees.put(1002, new Employee(1002, "E-BB", "bb@163", 1, new Department(102, "D-BB"))); employees.put(1003, new Employee(1003, "E-CC", "cc@163", 0, new Department(103, "D-CC"))); employees.put(1004, new Employee(1004, "E-DD", "dd@163", 0, new Department(104, "D-DD"))); employees.put(1005, new Employee(1005, "E-EE", "ee@163", 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.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<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); } }

然后,把Spring mvc的环境搭建好,注意:在web.xml中添加如下拦截器,实现将post请求变成delete或者put请求

<!--配置filter将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>

接下来,说一说这个小项目实现的功能,以及它的流程。 第一步,新建一个index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "www.w3/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 此处加斜杠的时候 点进去的路径为localhost:8080/emps 不加斜杠的是localhost:8080/springMVC-2/emps --> <a href="emps">Get All Employee</a> </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> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>

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>ID</td> <td>LAST NAME</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>

第四步,写一个添加新员工的功能。,点击list.jsp上面的添加新员工按钮,就会到对应的handler类中的方法中,然后会跳转到input.jsp页面

@RequestMapping(value="/emp" , method = RequestMethod.GET) public String input(Map<String ,Object> 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="www.springframework/tags/form" %> <%@ taglib prefix="c" uri="java.sun/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "www.w3/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </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> <% Map<Integer , String> genders = new HashMap<Integer,String>(); 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页面上应该添加如下代码

<form action="" method="post"> <input type="hidden" name="_method" value="DELETE"> </form> <script type="text/javascript"> $(function(){ $(".delete").click(function(){ var href = $(this).attr("href"); $("form").attr("action",href).submit(); return false; }); }) </script>

为了让静态页面有效果,必须在springmvc.xml配置文件中添加:

<!-- 可以在 SpringMVC 的配置文件中配置 <mvc:default-servlet-handler/> 的方式解决静态资源的问题: <mvc:default-servlet-handler/> 将在 SpringMVC 上下文中定义一个 – DefaultServletHttpRequestHandler,它会对进入 DispatcherServlet 的 请求进行筛查,如果发现是没有经过映射的请求,就将该请求交由 WEB 应用服务器默认的 Servlet 处理, 如果不是静态资源的请求,才由DispatcherServlet 继续处理一般 WEB 应用服务器默认的 Servlet 的名称都是 default。 若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 --> <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<String ,Object> 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"; }

本文标签: 项目springMVC