1、首先创建两个bean类,Employee(职工)和Department(部门),一个部门可以有多个职工

Employee类(属性:职工ID:id;姓名:lastName;邮箱:email;性别:gender;所属部门:department)

 package com.bwlu.bean;
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
public Employee() { }
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 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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department=" + department
+ "]";
}
}

Employee

Department类(属性:部门ID:id;部门名称:departmentName)

 package com.bwlu.bean;
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+ "]";
}
}

Department

2、然后分别实现两个bean类的Dao层方法(没有连接数据库,采用Map存储数据)

EmployeeDao类(添加和更新:save();获取:getAll()和get();删除:delete())

 package com.bwlu.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.bwlu.bean.Department;
import com.bwlu.bean.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);
}
}

EmployeeDao

DepartmentDao类(获取:getDepartments()和getDepartment())

 package com.bwlu.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.bwlu.bean.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);
}
}

DepartmentDao

3、前端页面的实现,一共有三个页面,显示页面(showEmployee.jsp),详情页面(detail.jsp),添加和修改页面(addOrEdit.jsp)

showEmployee.jsp,采用jstl标签进行遍历,

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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>员工列表</title>
<script type="text/javascript" src="<%=basePath %>public/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function delConfirm(id){
var b=confirm("确定删除吗?");
if(b){
$(function(){
//REST请求风格的url【delete】
var url="${pageContext.request.contextPath}/Employee/delete/"+id;
//将REST请求风格的url绑定到form表单的action属性中,并做提交
$("#delForm").attr("action",url).submit();
});
}
}
</script>
</head>
<body>
<div align="center">
<a class="aBtn" id="add" href='<c:url value="/Employee/goAddOREdit?id="></c:url>'>添加</a>
<table>
<c:choose>
<c:when test="${not empty employeeList }">
<tr><th>ID</th><th>姓名</th><th>邮箱</th><th>性别</th><th>部门</th><th>操作</th></tr>
<c:forEach var="employee" items="${employeeList }">
<tr><td>${employee.id }</td><td>${employee.lastName }</td><td>${employee.email }</td>
<td>${employee.gender==0?'女':'男'}</td>
<td>${employee.department.departmentName }</td>
<td><a href='<c:url value="/Employee/detail/${employee.id }"></c:url>'>详情</a>
<a href='<c:url value="/Employee/goAddOREdit?id=${employee.id }"></c:url>'>修改</a>
<a onclick="delConfirm(${employee.id })">删除</a></td></tr>
</c:forEach>
</c:when>
<c:otherwise>
暂无数据
</c:otherwise>
</c:choose>
</table>
</div>
<!-- 用来将post请求转化为delete请求 -->
<form id="delForm" action="" method="post">
<input type="hidden" name="_method" value="delete">
</form>
</body>
</html>

detail.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!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>详情页面</title>
</head>
<body>
<div align="center">
<form:form action="" menthod="post"modelAttribute="employee"><!-- modelAttribute属性指定绑定的模型属性 -->
ID:<form:input path="id"/><br><!-- path就是input标签的name属性 -->
姓名:<form:input path="lastName"/><br>
邮箱:<form:input path="email"/><br>
性别:<input type="text" value="${employee.gender==0?'女':'男'}"><br><!-- 这里不知道用form标签怎么处理 -->
部门:<form:input path="department.departmentName"/><br>
<a href="${pageContext.request.contextPath}/Employee/show">返回</a>
</form:form>
</div>
</body>
</html>

addOrEdit.jsp

 <%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>新增和修改页面</title>
</head>
<body>
<div align="center">
<form:form action="${pageContext.request.contextPath}/Employee/addOrUpdate" menthod="post" modelAttribute="employee">
<!-- 如果employee.id不为null,则将post请求转化为put请求 -->
<c:if test="${not empty employee.id }">
<input type="hidden" name="_method" value="put">
</c:if>
<input type="hidden" name="id" value="${employee.id }">
姓名:<form:input path="lastName"/><br>
邮箱:<form:input path="email"/><br>
<%
Map<String,Object> genderMap=new HashMap<String,Object>();
genderMap.put("0", "女");
genderMap.put("1", "男");
request.setAttribute("genderMap", genderMap);
%>
<!-- 进行修改时,性别和部门会自动匹配,不用我们自己设置 -->
性别:<form:radiobuttons path="gender"items="${genderMap }"/><br><!-- 运行时自动生成单选钮 -->
部门:<form:select path="department.id"items="${departList }"
itemLabel="departmentName"itemValue="id"><!-- 运行时自动生成下拉列表 -->
</form:select><br>
<input type="submit" value="提交">
</form:form>
</div>
</body>
</html>

SpringMVC的<form:form>标签简介

4、在后台写相应的方法

 @Controller
@RequestMapping("/Employee")
public class EmployeeController {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
@RequestMapping(value="/show",method=RequestMethod.GET)
public String showEmployee(Model m){//显示所有职工
Collection<Employee> employeeList=new ArrayList<Employee>();
Collection<Department> departList=new ArrayList<Department>();
employeeList=employeeDao.getAll();
departList=departmentDao.getDepartments();
m.addAttribute("employeeList", employeeList);
m.addAttribute("departList", departList);
return "employee/showEmployee";
}
@RequestMapping(value="/goAddOREdit",method=RequestMethod.GET)
public String goAddOREdit(Model m,@RequestParam(value="id") Integer id){//去添加和修改页面
Employee employee=new Employee();
Collection<Department> departList=new ArrayList<Department>();
if(id!=null)
employee=employeeDao.get(id);
departList=departmentDao.getDepartments();
m.addAttribute("employee", employee);
m.addAttribute("departList", departList);
return "employee/addOrEdit";
}
@RequestMapping(value="/addOrUpdate",method=RequestMethod.POST)
public String add(Employee employee){//添加职工
employeeDao.save(employee);
return "redirect:/Employee/show";
}
@RequestMapping(value="/addOrUpdate",method=RequestMethod.PUT)
public String update(Employee employee){//修改职工
employeeDao.save(employee);
return "redirect:/Employee/show";
}
@RequestMapping(value="/detail/{id}",method=RequestMethod.GET)
public String detail(Model m,@PathVariable(value="id") Integer id){//职工详情
Employee employee=employeeDao.get(id);
m.addAttribute("employee", employee);
return "employee/detail";
}
@RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable(value="id") Integer id) throws IOException{//删除职工
employeeDao.delete(id);
return "redirect:/Employee/show";
}
}

使用REST请求风格需要在web.xml中进行配置,请参见 如何使用REST请求风格

如何用Spring框架的<form:form>标签实现REST风格的增删改查操作的更多相关文章

  1. 【OF框架】新建库表及对应实体,并实现简单的增删改查操作,封装操作标准WebApi

    准备 搭建好项目框架及数据库,了解框架规范. 1.数据库表和实体一一对应,表名实体名名字相同,用小写,下划线连接.字段名用驼峰命名法,首字母大写. 2.实体放在Entities目录下,继承Entity ...

  2. 搭建ssm框架,可实现登录和数据展示以及增删改查

    需求: 后台使用ssm(spring-springMVC-mybatis)进行整合 前台使用bootstrap框架 前后台交互使用Ajax进行发送 表结构: 登录页面后显示所有用户信息,可对每条进行增 ...

  3. SSM框架入门——整合SSM并实现对数据的增删改查功能(Eclipse平台)

    一.搭建框架环境 整个项目结构如下: 搭建SSM步骤如下: (1)准备好三大框架的jar包,如图所示 (2)在Eclipse中创建一个web project ,并把这些jar包粘贴到lib文件夹中. ...

  4. 初识Hibernate框架,进行简单的增删改查操作

    Hibernate的优势 优秀的Java 持久化层解决方案  (DAO) 主流的对象—关系映射工具产品 简化了JDBC 繁琐的编码 将数据库的连接信息都存放在配置文件 自己的ORM框架 一定要手动实现 ...

  5. jquery-easyui实现页面布局和增删改查操作(SSH2框架支持)转载

    http://blessht.iteye.com/blog/1069749/ 已注册:ooip 关联的csdn 前几天心血来潮用jquery-easyui+spring.struts2.hiberna ...

  6. 初识hibernate框架之一:进行简单的增删改查操作

    Hibernate的优势 l 优秀的Java 持久化层解决方案  (DAO) l 主流的对象—关系映射工具产品 l 简化了JDBC 繁琐的编码 l 将数据库的连接信息都存放在配置文件 l 自己的ORM ...

  7. Spring boot 入门三:SpringBoot用JdbcTemplates访问Mysql 实现增删改查

    建表脚本 -- create table `account`DROP TABLE `account` IF EXISTSCREATE TABLE `account` ( `id` int(11) NO ...

  8. spring的mybatis-puls 配置,增删改查操作,分页

    pom <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or ...

  9. 【java学习】spring mvc 公共dao的实现,定义基本的增删改查

    接口类: package com.blog.db.dao; import com.blog.util.Pagination; import java.util.List; public interfa ...

随机推荐

  1. jQuery整理笔记八----jQuery的Ajax

    Ajax,我一直读的是"阿贾克斯",据当时大学老师讲该读音出处是依据当年风靡欧洲的荷兰足球俱乐部阿贾克斯的名字来的,我认为说法挺靠谱的. jQuery封装了Ajax的交互过程,用户 ...

  2. mongo 过滤查询条件后分组、排序

    描述:最近业主有这么一个需求,根据集合中 时间段进行过滤,过滤的时间时间段为日期类型字符串,需要根据某一日期进行截取后.进行分组,排序 概述题目:根据createTime时间段做查询,然后以 天进行分 ...

  3. hihoCoder 1549 或运算和

    #1549 : 或运算和 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 给定N个数A1...AN (0 <= Ai < 220) 和一个正整数K,我们用An ...

  4. 浅谈Spring框架注解的用法分析

    原文出处: locality 1.@Component是Spring定义的一个通用注解,可以注解任何bean. 2.@Scope定义bean的作用域,其默认作用域是”singleton”,除此之外还有 ...

  5. float 的先后顺序 理解流

    <!DOCTYPE html><html><head><style> p{float:right;}</style></head> ...

  6. 高并发服务器建议调小 TCP 协议的 time_wait 超时时间

    说明:操作系统默认 240 秒后,才会关闭处于 time_wait 状态的连接,在高并发访问下,服 务器端会因为处于 time_wait 的连接数太多,可能无法建立新的连接,所以需要在服务器上 调小此 ...

  7. You can add an index on a column that can have NULL values if you are using the MyISAM, InnoDB, or MEMORY storage engine.

    w https://dev.mysql.com/doc/refman/5.7/en/create-index.html MySQL :: MySQL 5.7 Reference Manual :: B ...

  8. jquery on 确认删除

    $(document).on('click', '.delbtn', function() {         if (confirm("确定要删除吗?")) {          ...

  9. ELBO 与 KL散度

    浅谈KL散度 一.第一种理解 相对熵(relative entropy)又称为KL散度(Kullback–Leibler divergence,简称KLD),信息散度(information dive ...

  10. Scrapy框架2

    一.进程.线程.协成 1.进程.线程.协成之间的关系          1.  线程是计算机中最小的工作单元.              2. 进程是提供资源供n个线程使用,即进程是最小的管理单元. ...