SpringMVC实例之RESTful风格进行CRUD(学习笔记)

根据:springMVC工作原理

一、 添加所有员工信息

  1. 显示添加页面
  2. URL:emp
  3. 请求方式:GET
  4. jsp页面
  5. 添加请求方式:POST
  6. 显示效果:完成添加,重定向到 list 页
    在这里插入图片描述

二、展示所有员工信息

  • URI:emps
  • 请求方式:GET
  • 显示效果
    在这里插入图片描述

三、删除单个员工信息

URL:emp/{id}

  • 请求方式:DELETE
  • 删除后效果:对应记录从数据表中删除

四、更改单个员工信息

  1. 显示修改页面
    • URI:emp/{id}
    • 请求方式:GET
    • 显示效果:回显表单。
  2. 修改员工信息
    • URI:emp
    • 请求方式:PUT
    • 显示效果:完成修改,重定向到 list 页面。
    为了方便数据的操作管理定义了两个类存储数据
  • (Employee类和Department类)
    在这里插入图片描述

具体介绍:

  1. 实体类:
  • Employee、Department
  • EmployeeHandler
  • EmployeeDao、DepartmentDao
  1. 相关的页面
  • list.jsp
  • input.jsp
  • edit.jsp
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
	}

}

package com.atguigu.springmvc.crud.entities;

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
				+ "]";
	}
	
}

其中DepartmentDao类和Employee类又初始化时自定义了五条初始数据
EmployeeDao 类

package com.atguigu.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.atguigu.springmvc.crud.entities.Department;
import com.atguigu.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(1, new Employee(1, "ZAS", "[email protected]", 1, new Department(101, "JAVA")));
		employees.put(2, new Employee(2, "ZDS", "[email protected]", 0, new Department(102, "C++")));
		employees.put(3, new Employee(3, "LSD", "[email protected]", 0, new Department(103, "C#")));
		employees.put(4, new Employee(4, "FSD", "[email protected]", 0, new Department(104, "Python")));
		employees.put(5, new Employee(5, "ERF", "[email protected]", 1, new Department(105, "Pycharm")));
	}

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

EmployeeDao类

package com.atguigu.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.atguigu.springmvc.crud.entities.Department;
import com.atguigu.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(1, new Employee(1, "ZAS", "[email protected]", 1, new Department(101, "JAVA")));
		employees.put(2, new Employee(2, "ZDS", "[email protected]", 0, new Department(102, "C++")));
		employees.put(3, new Employee(3, "LSD", "[email protected]", 0, new Department(103, "C#")));
		employees.put(4, new Employee(4, "FSD", "[email protected]", 0, new Department(104, "Python")));
		employees.put(5, new Employee(5, "ERF", "[email protected]", 1, new Department(105, "Pycharm")));
	}

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

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
	<script type="text/javascript">
$(function(){
    
    
		
		$("#testJson").click(function(){
    
    
		
			var url = this.href;
			var args = {
    
    };
			$.post(url, args, function(data){
    
    
				alert(1);
				for(var i = 0; i < data.length; i++){
    
    
					var id = data[i].id;
					var lastName = data[i].lastName;
					
					alert(id + ": " + lastName);
				}
			});
			return false;
		});
	})
	</script>


	<a href="testJson" id="testJson">Test Json</a>
	<br><br>
	<a href="emps">List All Employees</a>
	<br>
	<br>

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>
	<br>
	<br>
	<!-- el表达式 
	${pageContext.request.contextPath }获取 localhost:8080/
	获取绝对路径
	
	-->

	<form:form action="${pageContext.request.contextPath }/emp"
		method="POST" modelAttribute="employee">

		<form:errors path="*"></form:errors>
		<br>

		<c:if test="${employee.id == null }">
			<!-- path 属性对应 html 表单标签的 name 属性值 -->
			LastName: <form:input path="lastName" />
			<form:errors path="lastName"></form:errors>
		</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" />
		<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: 
		<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多个表单组件标签目的

  1. form 标签

一般情况下,通过 GET 请求获取表单页面,而通过POST 请求提交表单页面,因此获取表单页面和提交表单 页面的 URL
是相同的。只要满足该最佳条件的契约,<form:form > 标签就无需通过 action 属性指定表单提交的 URL

可以通过 modelAttribute 属性指定绑定的模型属性,若没有指定该属性,则默认从 request 域对象中读取command
的表单bean,如果该属性值也不存在,则会 发生错误

  1. 表单标签

SpringMVC 提供了多个表单组件标签,如 < form:input/>、
< form:select/>
等,用以绑定表单字段的属性值,它们的共有属性如下:
– path:表单字段,对应 html 元素的 name 属性,支持级联属性
–htmlEscape:是否对表单值的 HTML 特殊字符进行转换,默认值 为 true
– cssClass:表单组件对应的 CSS
样式类名
– cssErrorClass:表单组件的数据存在错误时,采取的 CSS 样式

form:input、form:password、form:hidden、form:textarea :对应 HTML 表单的
text、password、hidden、textarea 标签 • form:radiobutton:单选框组件标签,当表单 bean
对应的 属性值和 value 值相等时,单选框被选中 • form:radiobuttons:单选框组标签,用于构造多个单选 框–
items:可以是一个 List、String[] 或 Map – itemValue:指定 radio 的 value 值。可以是集合中
bean 的一个 属性值 – itemLabel:指定 radio 的 label 值 – delimiter:多个单选框可以通过
delimiter 指定分隔符
form:checkbox:复选框组件。用于构造单个复选框 • form:checkboxs:用于构造多个复选框。使用方式同
form:radiobuttons 标签
• form:select:用于构造下拉框组件。使用方式同
form:radiobuttons 标签
• form:option:下拉框选项组件标签。使用方式同
form:radiobuttons 标签
• form:errors:显示表单组件或数据校验所对应的错误 – <form:errors path= “ ” /> :显示表单所有的错误
– <form:errors path= “ user
” /> :显示所有以 user 为前缀的属性对应
的错误
– <form:errors path= “ username” /> :显示特定表单对象属性的错误

  1. 注意:
    可以通过 modelAttribute 属性指定绑定的模型属性,若没有指定该属性,则默认从 request 域对象中读取 command 的表单 bean如果该属性值也不存在,则会发生错误。
<%@ 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>Insert title here</title>
<!--  
	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>
</head>
<body>
	
	<form action="" method="POST">
		<input type="hidden" name="_method" value="DELETE"/>
	</form>
	
	<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>
	
</body>
</html>
package com.atguigu.springmvc.crud.entities;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
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.atguigu.springmvc.crud.dao.DepartmentDao;
import com.atguigu.springmvc.crud.dao.EmployeeDao;
import com.atguigu.springmvc.crud.entities.Employee;

@Controller
public class EmployeeHandler {
    
    

	@Autowired
	private EmployeeDao employeeDao;

	@Autowired
	private DepartmentDao departmentDao;

	@ModelAttribute
	public void GetElement(@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";

	}
    //根据id显示数据
	@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";
	}
    //根据id删除数据
	@RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Integer id) {
    
    
		employeeDao.delete(id);
		System.out.println("删除成功");
		return "redirect:/emps";
	}
    //校验数据
	@RequestMapping(value = "/emp", method = RequestMethod.POST)
	public String save(@Valid Employee employee, Errors result, Map<String, Object> map) {
    
    
		System.out.println("save: " + employee);

		if (result.getErrorCount() > 0) {
    
    
			System.out.println("god,出错了!");

			for (FieldError error : result.getFieldErrors()) {
    
    
				System.out.println(error.getField() + ":" + error.getDefaultMessage());
			}

			// 若验证出错, 则转向定制的页面
			map.put("departments", departmentDao.getDepartments());
			return "input";
		}

		employeeDao.save(employee);
		return "redirect:/emps";
	}

	@RequestMapping(value = "/emp", method = RequestMethod.GET)
	public String input(Map<String, Object> map) {
    
    
		System.out.println("测试get方法");
		map.put("departments", departmentDao.getDepartments());
		map.put("employee", new Employee());
		return "input";
	}

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

}

配置文件

  1. 导入jar包
    在这里插入图片描述

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:c="http://www.springframework.org/schema/c"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- 配置自动扫描的包 -->
	<context:component-scan
		base-package="com.atguigu.springmvc,com.qst,com.qsaat.list"></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>

	<mvc:default-servlet-handler />
	<mvc:annotation-driven></mvc:annotation-driven>



	<!-- 配置国际化资源文件 -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="i18n"></property>
	</bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<!-- 配置 SpringMVC 的 DispatcherServlet -->
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 配置 HiddenHttpMethodFilter: 把 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>

</web-app>
/**
 *                  ___====-_  _-====___
 *            _--^^^#####//      \\#####^^^--_
 *         _-^##########// (    ) \\##########^-_
 *        -############//  |\^^/|  \\############-
 *      _/############//   (@::@)   \\############\_
 *     /#############((     \\//     ))#############\
 *    -###############\\    (oo)    //###############-
 *   -#################\\  / VV \  //#################-
 *  -###################\\/      \//###################-
 * _#/|##########/\######(   /\   )######/\##########|\#_
 * |/ |#/\#/\#/\/  \#/\##\  |  |  /##/\#/  \/\#/\#/\#| \|
 * `  |/  V  V  `   V  \#\| |  | |/#/  V   '  V  V  \|  '
 *    `   `  `      `   / | |  | | \   '      '  '   '
 *                     (  | |  | |  )
 *                    __\ | |  | | /__
 *                   (vvv(VVV)(VVV)vvv)                
 *                        神兽保佑
 *                       代码无BUG!
 */

猜你喜欢

转载自blog.csdn.net/weixin_44763595/article/details/108111409