如何用Spring框架的<form:form>标签实现REST风格的增删改查操作
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>
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风格的增删改查操作的更多相关文章
- 【OF框架】新建库表及对应实体,并实现简单的增删改查操作,封装操作标准WebApi
准备 搭建好项目框架及数据库,了解框架规范. 1.数据库表和实体一一对应,表名实体名名字相同,用小写,下划线连接.字段名用驼峰命名法,首字母大写. 2.实体放在Entities目录下,继承Entity ...
- 搭建ssm框架,可实现登录和数据展示以及增删改查
需求: 后台使用ssm(spring-springMVC-mybatis)进行整合 前台使用bootstrap框架 前后台交互使用Ajax进行发送 表结构: 登录页面后显示所有用户信息,可对每条进行增 ...
- SSM框架入门——整合SSM并实现对数据的增删改查功能(Eclipse平台)
一.搭建框架环境 整个项目结构如下: 搭建SSM步骤如下: (1)准备好三大框架的jar包,如图所示 (2)在Eclipse中创建一个web project ,并把这些jar包粘贴到lib文件夹中. ...
- 初识Hibernate框架,进行简单的增删改查操作
Hibernate的优势 优秀的Java 持久化层解决方案 (DAO) 主流的对象—关系映射工具产品 简化了JDBC 繁琐的编码 将数据库的连接信息都存放在配置文件 自己的ORM框架 一定要手动实现 ...
- jquery-easyui实现页面布局和增删改查操作(SSH2框架支持)转载
http://blessht.iteye.com/blog/1069749/ 已注册:ooip 关联的csdn 前几天心血来潮用jquery-easyui+spring.struts2.hiberna ...
- 初识hibernate框架之一:进行简单的增删改查操作
Hibernate的优势 l 优秀的Java 持久化层解决方案 (DAO) l 主流的对象—关系映射工具产品 l 简化了JDBC 繁琐的编码 l 将数据库的连接信息都存放在配置文件 l 自己的ORM ...
- Spring boot 入门三:SpringBoot用JdbcTemplates访问Mysql 实现增删改查
建表脚本 -- create table `account`DROP TABLE `account` IF EXISTSCREATE TABLE `account` ( `id` int(11) NO ...
- spring的mybatis-puls 配置,增删改查操作,分页
pom <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or ...
- 【java学习】spring mvc 公共dao的实现,定义基本的增删改查
接口类: package com.blog.db.dao; import com.blog.util.Pagination; import java.util.List; public interfa ...
随机推荐
- Android 定时器Timer的使用
定时器有什么用 在我们Android客户端上有时候可能有些任务不是当时就执行,而是过了一个规定的时间在执行此次任务.那么这个时候定时器的作用就非常有用了.首先开启一个简单的定时器 Timer time ...
- (转)gethostbyname() -- 用域名或主机名获取IP地址
struct hostent *gethostbyname(const char *name); 这个函数的传入值是域名或者主机名,例如"www.google.cn"等等.传出值, ...
- 【BZOJ3122】[Sdoi2013]随机数生成器 BSGS+exgcd+特判
[BZOJ3122][Sdoi2013]随机数生成器 Description Input 输入含有多组数据,第一行一个正整数T,表示这个测试点内的数据组数. 接下来T行,每行有五个整数p,a,b, ...
- isnull在order by中的使用——让我长见识了
select * from VisitLogorder by ISNULL(NextVisitDate,'2299-01-01') 此sql的作用是查找表中的数据,并按照NextVisitDate字段 ...
- Spring 缓存注解@Cacheable 在缓存时候 ,出现了第一次进入调用 方法 ,第二次不调用的异常
代码: @Override @Cacheable(value = CACHE_NAME, key = "'CartItemkey_'+#uId") public List<S ...
- 路径规划 Adjacency matrix 传球问题
建模 问题是什么 知道了问题是什么答案就ok了 重复考虑 与 重复计算 程序可以重复考虑 但往目标篮子中放入时,放不放把握好就ok了. 集合 交集 并集 w 路径规划 字符串处理 42423 424 ...
- Kuratowski's and Wagner's theorems
w https://en.wikipedia.org/wiki/Planar_graph The Polish mathematician Kazimierz Kuratowski provided ...
- Bootstrap学习-排版-表单
1.标题 <h1>~<h6>,所有标题的行高都是1.1(也就是font-size的1.1倍). 2.副标题 <small>,行高都是1,灰色(#999) <h ...
- 前端基础 & 初识JS(JavaScript)
JavaScript概述 JavaScript的历史 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在CEnvi软件中),后将其改名ScriptEase(客 ...
- 前端框架之jQuery(二)----轮播图,放大镜
事件 页面载入 ready(fn) //当DOM载入就绪可以查询及操纵时绑定一个要执行的函数. $(document).ready(function(){}) -----------> ...