最近在学习springMVC,通过视频学习到一些,特此来写篇博客来加深记忆。
本篇博客是实现列表的增删改查,没有使用数据库,原始的数据是写死的。
先看效果图
列表界面
新增界面
修改界面
项目视图
所需要的包
在实现功能前要搭好springMVC框架,这个我就不在此处说明,不懂的话可以参考我之前的博客
首先我们先写好数据,建立四个类
Department
package com.zjq.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
+ "]";
}
}
Employee
package com.zjq.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
}
}
DepartmentDao
package com.zjq.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.zjq.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);
}
}
EmployeeDao
package com.zjq.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.zjq.springmvc.crud.entities.Department;
import com.zjq.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.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);
}
}
1、第一步实现列表的展示
list.jsp
<c:if test="${empty requestScope.employees }">
没有任何员工信息.
</c:if>
<c:if test="${!empty requestScope.employees }">
<table border="1" cellpadding="10" cellspacing="0">
<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.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>
<br><br>
<a href="emp">Add New Employee</a>
要实现上述标签必须在头部加上
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
刚开始写一个界面实现跳转
index.jsp
<%@ 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="emps">List All Employees</a>
</body>
</html>
现在开始写方法
package com.zjq.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.zjq.springmvc.crud.dao.DepartmentDao;
import com.zjq.springmvc.crud.dao.EmployeeDao;
import com.zjq.springmvc.crud.entities.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeedao;
@Autowired
private DepartmentDao departmentDao;
@RequestMapping("/emps")
public String list(Map<String, Object> map) {
map.put("employees", employeedao.getAll());
return "list";
}
}
2、第二步实现增加(增加界面与修改与修改界面是一致的)
input.jsp
<%@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" %>
<!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>
<!--
1. 为什么使用form标签呢?
可以更快速的开发出表单页面,而且可以更方便的进行表单值的回显
2. 注意:
可以通过 modelAttribute 属性指定绑定的模型属性,
若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean
如果该属性值也不存在,则会发生错误。
-->
<!-- modelAttribute="employee"此处employee与map.put("employee", new Employee()) 一致 -->
<form:form action="${pageContext.request.contextPath }/emp" method="POST" modelAttribute="employee">
<c:if test="${employee.id == null}">
<!-- path 属性对应HTML表单标签的name属性值 -->
LastName: <form:input path="lastName"/>
</c:if>
<c:if test="${employee.id != null }">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT"/>
<%-- 对于 _method 不能使用 form:hidden 标签, 因为 modelAttribute 对应的 bean 中没有 _method 这个属性 --%>
<%--
<form:hidden path="_method" value="PUT"/>
--%>
</c:if>
<br>
Email: <form:input path="email"/>
<br>
<%
Map<String, String> genders = new HashMap();
genders.put("1", "Male");
genders.put("0", "Female");
request.setAttribute("genders", genders);
%>
Gender:
<br>
<form:radiobuttons path="gender" items="${genders }" delimiter="<br>"/>
<br>
Department: <form:select path="department.id"
items="${departments }" itemLabel="departmentName" itemValue="id"></form:select>
<br>
<input type="submit" value="Submit"/>
</form:form>
</body>
</html>
中间特别注意这个
实现这个必须在springMVC.xml文件里加上 ,否则会出错
<mvc:annotation-driven></mvc:annotation-driven>
实现的方法
@RequestMapping(value="/emp", method=RequestMethod.POST)
public String save(Employee employee) {
employeedao.save(employee);
return "redirect:/emps";
}
@RequestMapping(value="emp", method = RequestMethod.GET)
public String input(Map<String, Object> map) {
map.put("departments",departmentDao.getDepartments());
map.put("employee", new Employee());
return "input";
}
3、实现删除功能
@RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
employeedao.delete(id);
return "redirect:/emps";
}
我们发现这里面是DELETE请求,传统是POT与GET请求
所以需在jsp文件里将POST请求转为DELETE请求
要实现删除的功能,需在编写js方法
<!--
SpringMVC处理静态资源:
1. 为什么会有这样的问题:
优雅的 REST 风格的资源URL 不希望带 .html 或 .do 等后缀
若将 DispatcherServlet 请求映射配置为 /,
则 Spring MVC 将捕获 WEB 容器的所有请求, 包括静态资源的请求, SpringMVC 会将他们当成一个普通请求处理,
因找不到对应处理器将导致错误。
2. 解决: 在 SpringMVC 的配置文件中配置 <mvc:default-servlet-handler/>
-->
<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>
在springmvc.xml文件里加上
<!--
default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的
Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理
一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定
-->
<mvc:default-servlet-handler/>
4、最后一步实现数据的修改
@ModelAttribute
public void getEmployee(@RequestParam(value="id",required=false) Integer id,
Map<String, Object> map){
if(id != null){
map.put("employee", employeedao.get(id));
}
}
@RequestMapping(value="/emp", method=RequestMethod.PUT)
public String update(Employee employee){
employeedao.save(employee);
return "redirect:/emps";
}
@RequestMapping(value="/emp/{id}", method = RequestMethod.GET)
public String input(@PathVariable("id") Integer id, Map<String, Object> map) {
map.put("employee", employeedao.get(id));
map.put("departments",departmentDao.getDepartments());
return "input";
}
增加的操作要实现用户名不被修改,采用@ModelAttribute实现,先把数据存在里面,这样修改就不会出现用户名出现空值现象。里面的PUT的请求与DELETE请求实现方法是一致的。
此处要加绝对路径,项目在开发时基本都是用绝对路径,使用相对路径难免会出现错误
需要代码者可以在此下载:链接:https://pan.baidu.com/s/16rkOSdTRR-77_9Nhm7qf7A ,提取码:ccrz
第一次写这么详细的博客,肯定有许多不足之处,有些专业术语不会怎么用,如果有大佬来到此处,一笑了之即可,如果可以还望给予些建议,小弟感激不尽!