学习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 继续处理

时间: 2024-10-08 06:26:40

学习SpringMVC(十五)之CRUD操作的相关文章

javascript基础学习(十五)

javascript之cookie 学习要点: cookie介绍 创建与获取cookie cookie的编码 cookie的生存期 cookie的路径 cookie的domain cookie的secure 一.cookie介绍 cookie实际上就是一些信息,这些信息以文件的形式存储在客户端计算机上.在javascript中,cookie主要用来保存状态,或用于识别身份. 二.创建与获取cookie 创建cookie的语法代码如下所示:document.cookie="name=value&q

hbase 学习(十五)缓存机制以及可以利用SSD作为存储的BucketCache

下面介绍Hbase的缓存机制: a.HBase在读取时,会以Block为单位进行cache,用来提升读的性能 b.Block可以分类为DataBlock(默认大小64K,存储KV).BloomBlock(默认大小128K,存储BloomFilter数据).IndexBlock(默认大小128K,索引数据,用来加快Rowkey所在DataBlock的定位) c.对于一次随机读,Block的访问顺序为BloomBlock.IndexBlock.DataBlock,如果Region下面的StoreFi

[原创]java WEB学习笔记6:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------

JavaScript学习总结(十五)——Function类

在JavaScript中,函数其实是对象,每个函数都是Function类的实例,既然函数对象,那么就具有自己的属性和方法,因此,函数名实际上也是一个指向函数对象的指针,不会与某个函数绑定. 一.函数的声明 方式一:常规方式 1 function sum1(num1,num2){ 2 return num1+num2 3 } 方式二:函数表达式 1 var sum2=function(num1,num2){ 2 return num1+num2; 3 }; 方式三:动态创建函数(这种方式用得不多)

Swift 学习笔记十五:扩展

扩展就是向一个已有的类.结构体或枚举类型添加新功能(functionality).扩展和 Objective-C 中的分类(categories)类似.(不过与Objective-C不同的是,Swift 的扩展没有名字.) Swift 中的扩展可以: 1.添加计算型属性和计算静态属性 2.定义实例方法和类型方法 3.提供新的构造器 4.定义下标 5.定义和使用新的嵌套类型 6.使一个已有类型符合某个协议 一.扩展属性,构造器,方法 class Human{ var name:String? va

Python学习系列(五)(文件操作及其字典)

Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件 在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出,也可以指定每次read读多少字节,例如: 1 #coding:utf-8 2 fn='test1.py' 3 fp=open(fn,'r') #以读的方式打开文件,文件必须首先存在和,.文件在同一目录下py 4 print 'reading pos:',fp.tell() 5 r=fp.read(20) #

laravel3学习笔记(十五)

原作者博客:ieqi.net ==================================================================================================== 异常与日志 在应用中,我们总会遇到各种问题.各种异常,这时,记录异常发生时的状态就很重要,所以异常与日志是有着天然的关系的. 关于异常与日志的配置在文件 application/config/error.php 中. 文件中有四个配置项: 'ignore' => ar

C++语言学习(十五)——C++抽象类与接口

C++语言学习(十五)--C++抽象类与接口 一.抽象类与接口 1.抽象类简介 面向对象的抽象类用于表示现实世界的抽象概念,是一种只能定义类型,不能产生对象的类(不能实例化),只能被继承并被重写相关函数,直接特征是相关函数没有完整实现.C++语言没有抽象类的概念,通过纯虚函数实现抽象类.纯虚函数是指定义原型的成员函数,C++中类如果存在纯虚函数就成为了抽象类.抽象类只能用作父类被继承,子类必须实现父类纯虚函数的具体功能,如果子类没实现纯虚函数,子类也为抽象类.抽象类不可以定义对象,但是可以定义指

学习进度十五

  第十五周 学习时间 12 代码行 800 博客篇 2 所学内容 关于单词链以及android的数据库 原文地址:https://www.cnblogs.com/NCLONG/p/10988948.html