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

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

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

 1 package com.bwlu.bean;
 2 public class Employee {
 3     private Integer id;
 4     private String lastName;
 5     private String email;
 6     //1 male, 0 female
 7     private Integer gender;
 8     private Department department;
 9     public Employee() {
10
11     }
12     public Employee(Integer id, String lastName, String email, Integer gender,
13             Department department) {
14         super();
15         this.id = id;
16         this.lastName = lastName;
17         this.email = email;
18         this.gender = gender;
19         this.department = department;
20     }
21     public Integer getId() {
22         return id;
23     }
24     public void setId(Integer id) {
25         this.id = id;
26     }
27     public String getLastName() {
28         return lastName;
29     }
30     public void setLastName(String lastName) {
31         this.lastName = lastName;
32     }
33     public String getEmail() {
34         return email;
35     }
36     public void setEmail(String email) {
37         this.email = email;
38     }
39     public Integer getGender() {
40         return gender;
41     }
42     public void setGender(Integer gender) {
43         this.gender = gender;
44     }
45     public Department getDepartment() {
46         return department;
47     }
48     public void setDepartment(Department department) {
49         this.department = department;
50     }
51     @Override
52     public String toString() {
53         return "Employee [id=" + id + ", lastName=" + lastName + ", email="
54                 + email + ", gender=" + gender + ", department=" + department
55                 + "]";
56     }
57 }

Employee

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

 1 package com.bwlu.bean;
 2 public class Department {
 3     private Integer id;
 4     private String departmentName;
 5     public Department() {
 6
 7     }
 8     public Department(int i, String string) {
 9         this.id = i;
10         this.departmentName = string;
11     }
12     public Integer getId() {
13         return id;
14     }
15     public void setId(Integer id) {
16         this.id = id;
17     }
18     public String getDepartmentName() {
19         return departmentName;
20     }
21     public void setDepartmentName(String departmentName) {
22         this.departmentName = departmentName;
23     }
24     @Override
25     public String toString() {
26         return "Department [id=" + id + ", departmentName=" + departmentName+ "]";
27     }
28 }

Department

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

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

 1 package com.bwlu.dao;
 2 import java.util.Collection;
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Repository;
 7 import com.bwlu.bean.Department;
 8 import com.bwlu.bean.Employee;
 9 @Repository
10 public class EmployeeDao {
11     private static Map<Integer, Employee> employees = null;
12     @Autowired
13     private DepartmentDao departmentDao;
14     static{
15         employees = new HashMap<Integer, Employee>();
16
17         employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
18         employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
19         employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
20         employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
21         employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE")));
22     }
23     private static Integer initId = 1006;
24     public void save(Employee employee){
25         if(employee.getId() == null){
26             employee.setId(initId++);
27         }
28         employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
29         employees.put(employee.getId(), employee);
30     }
31     public Collection<Employee> getAll(){
32         return employees.values();
33     }
34     public Employee get(Integer id){
35         return employees.get(id);
36     }
37     public void delete(Integer id){
38         employees.remove(id);
39     }
40 }

EmployeeDao

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

 1 package com.bwlu.dao;
 2 import java.util.Collection;
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import org.springframework.stereotype.Repository;
 6 import com.bwlu.bean.Department;
 7 @Repository
 8 public class DepartmentDao {
 9     private static Map<Integer, Department> departments = null;
10     static{
11         departments = new HashMap<Integer, Department>();
12         departments.put(101, new Department(101, "D-AA"));
13         departments.put(102, new Department(102, "D-BB"));
14         departments.put(103, new Department(103, "D-CC"));
15         departments.put(104, new Department(104, "D-DD"));
16         departments.put(105, new Department(105, "D-EE"));
17     }
18     public Collection<Department> getDepartments(){
19         return departments.values();
20     }
21     public Department getDepartment(Integer id){
22         return departments.get(id);
23     }
24 }

DepartmentDao

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

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

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4     String path = request.getContextPath();
 5     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 8 <html>
 9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11 <title>员工列表</title>
12 <script type="text/javascript" src="<%=basePath %>public/js/jquery-3.2.1.min.js"></script>
13 <script type="text/javascript">
14 function delConfirm(id){
15     var b=confirm("确定删除吗?");
16     if(b){
17         $(function(){
18             //REST请求风格的url【delete】
19             var url="${pageContext.request.contextPath}/Employee/delete/"+id;
20             //将REST请求风格的url绑定到form表单的action属性中,并做提交
21             $("#delForm").attr("action",url).submit();
22         });
23     }
24 }
25 </script>
26 </head>
27 <body>
28 <div align="center">
29     <a class="aBtn" id="add" href=‘<c:url value="/Employee/goAddOREdit?id="></c:url>‘>添加</a>
30     <table>
31         <c:choose>
32             <c:when test="${not empty employeeList }">
33                 <tr><th>ID</th><th>姓名</th><th>邮箱</th><th>性别</th><th>部门</th><th>操作</th></tr>
34                 <c:forEach var="employee" items="${employeeList }">
35                 <tr><td>${employee.id }</td><td>${employee.lastName }</td><td>${employee.email }</td>
36                     <td>${employee.gender==0?‘女‘:‘男‘}</td>
37                     <td>${employee.department.departmentName }</td>
38                     <td><a href=‘<c:url value="/Employee/detail/${employee.id }"></c:url>‘>详情</a>
39                         <a href=‘<c:url value="/Employee/goAddOREdit?id=${employee.id }"></c:url>‘>修改</a>
40                         <a onclick="delConfirm(${employee.id })">删除</a></td></tr>
41                 </c:forEach>
42             </c:when>
43             <c:otherwise>
44                 暂无数据
45             </c:otherwise>
46         </c:choose>
47     </table>
48 </div>
49 <!-- 用来将post请求转化为delete请求 -->
50 <form id="delForm" action="" method="post">
51     <input type="hidden" name="_method" value="delete">
52 </form>
53 </body>
54 </html>

detail.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 4 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <title>详情页面</title>
10 </head>
11 <body>
12 <div align="center">
13     <form:form action="" menthod="post"modelAttribute="employee"><!-- modelAttribute属性指定绑定的模型属性 -->
14         ID:<form:input path="id"/><br><!-- path就是input标签的name属性 -->
15         姓名:<form:input path="lastName"/><br>
16         邮箱:<form:input path="email"/><br>
17         性别:<input type="text" value="${employee.gender==0?‘女‘:‘男‘}"><br><!-- 这里不知道用form标签怎么处理 -->
18         部门:<form:input path="department.departmentName"/><br>
19         <a href="${pageContext.request.contextPath}/Employee/show">返回</a>
20     </form:form>
21 </div>
22 </body>
23 </html>

addOrEdit.jsp

 1 <%@page import="java.util.HashMap"%>
 2 <%@page import="java.util.Map"%>
 3 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 4 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 5 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 7 <html>
 8 <head>
 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
10 <title>新增和修改页面</title>
11 </head>
12 <body>
13 <div align="center">
14     <form:form action="${pageContext.request.contextPath}/Employee/addOrUpdate" menthod="post" modelAttribute="employee">
15         <!-- 如果employee.id不为null,则将post请求转化为put请求 -->
16         <c:if test="${not empty employee.id }">
17             <input type="hidden" name="_method" value="put">
18         </c:if>
19         <input type="hidden" name="id" value="${employee.id }">
20         姓名:<form:input path="lastName"/><br>
21         邮箱:<form:input path="email"/><br>
22         <%
23             Map<String,Object> genderMap=new HashMap<String,Object>();
24             genderMap.put("0", "女");
25             genderMap.put("1", "男");
26             request.setAttribute("genderMap", genderMap);
27         %>
28         <!-- 进行修改时,性别和部门会自动匹配,不用我们自己设置 -->
29         性别:<form:radiobuttons path="gender"items="${genderMap }"/><br><!-- 运行时自动生成单选钮 -->
30         部门:<form:select path="department.id"items="${departList }"
31 itemLabel="departmentName"itemValue="id"><!-- 运行时自动生成下拉列表 -->
32         </form:select><br>
33         <input type="submit" value="提交">
34     </form:form>
35 </div>
36 </body>
37 </html>

SpringMVC的<form:form>标签简介

4、在后台写相应的方法

 1 @Controller
 2 @RequestMapping("/Employee")
 3 public class EmployeeController {
 4     @Autowired
 5     private EmployeeDao employeeDao;
 6     @Autowired
 7     private DepartmentDao departmentDao;
 8     @RequestMapping(value="/show",method=RequestMethod.GET)
 9     public String showEmployee(Model m){//显示所有职工
10         Collection<Employee> employeeList=new ArrayList<Employee>();
11         Collection<Department> departList=new ArrayList<Department>();
12         employeeList=employeeDao.getAll();
13         departList=departmentDao.getDepartments();
14         m.addAttribute("employeeList", employeeList);
15         m.addAttribute("departList", departList);
16         return "employee/showEmployee";
17     }
18     @RequestMapping(value="/goAddOREdit",method=RequestMethod.GET)
19     public String goAddOREdit(Model m,@RequestParam(value="id") Integer id){//去添加和修改页面
20         Employee employee=new Employee();
21         Collection<Department> departList=new ArrayList<Department>();
22         if(id!=null)
23             employee=employeeDao.get(id);
24         departList=departmentDao.getDepartments();
25         m.addAttribute("employee", employee);
26         m.addAttribute("departList", departList);
27         return "employee/addOrEdit";
28     }
29     @RequestMapping(value="/addOrUpdate",method=RequestMethod.POST)
30     public String add(Employee employee){//添加职工
31         employeeDao.save(employee);
32         return "redirect:/Employee/show";
33     }
34     @RequestMapping(value="/addOrUpdate",method=RequestMethod.PUT)
35     public String update(Employee employee){//修改职工
36         employeeDao.save(employee);
37         return "redirect:/Employee/show";
38     }
39     @RequestMapping(value="/detail/{id}",method=RequestMethod.GET)
40     public String detail(Model m,@PathVariable(value="id") Integer id){//职工详情
41         Employee employee=employeeDao.get(id);
42         m.addAttribute("employee", employee);
43         return "employee/detail";
44     }
45     @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
46     public String delete(@PathVariable(value="id") Integer id) throws IOException{//删除职工
47         employeeDao.delete(id);
48         return "redirect:/Employee/show";
49     }
50 }
时间: 2024-10-22 14:22:53

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

python-django框架-orm相关继续&amp;ORM的增删改查操作_20191110

python-django框架-orm相关继续 orm不常用字段: 1,BigIntegerField(IntegerField):可以存手机号,也可以使用字符串存储手机号, - 长整型(有符号的) -9223372036854775808 - 9223372036854775807 2,BooleanField(Field) - 布尔值类型 3,DateTimeField(DateField) - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] 4,时间间

【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例

转载请注明出处:http://blog.csdn.net/qq_26525215 本文源自[大学之旅_谙忆的博客] 前面两篇博客已经将Hibernate的基础知识讲解得差不多了,差不多到写实例的时候了. 本篇只用hibernate进行单表的增删改查. 应用Hibernate,对students表进行增删改查. service层和DAO层,我都是直接写实现类了(因为这里主要是演示一下Hibernate的使用),如果是开发项目,注意一定要写接口! 准备数据库: 首先准备一个students表: cr

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

http://blessht.iteye.com/blog/1069749/ 已注册:ooip 关联的csdn 前几天心血来潮用jquery-easyui+spring.struts2.hibernate实现了一个系统的一小部分功能,下面给大家分享一下. 首先看运行效果: [图一:登录页] [图二:页面布局] [图三:用户编辑层] [图四:确认弹出框] 准备 easyui插件简介在这就不赘述了,大家可以在iteye上找到很多该插件的相关消息. 如果页面需要使用easyui插件,需要引进一下js和

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

Hibernate的优势 l 优秀的Java 持久化层解决方案  (DAO) l 主流的对象—关系映射工具产品 l 简化了JDBC 繁琐的编码 l 将数据库的连接信息都存放在配置文件 l 自己的ORM框架 l 一定要手动实现Hibernate(模拟Hibernate实现) 一:创建一个java project项目 如下图 2:创建一个大配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hib

CI(CodeIgniter)框架中的增删改查操作

我们创建一个模型( 项目目录/models/),请注意:模型名与文件名相同且必须继承数据核心类CI_Model,同时重载父类中的构造方法 CodeIgniter的数据函数类在 \models\User_model.php 连接数据库:$this->load->database(); class User_model extends CI_Model{ public function __construct(){ parent::__construct(); $this->load->

关于后盾网yii框架的学习小结(10)--使用AR类的增删改查

创建新的数据库的语句 <?php class CategoryController extends Controller{ public function filters(){ return array( 'accessControl', ); } public function accessRules(){ return array( //更加具体化 // array( // 'allow', // 'actions'=>array('del','add'), // 'users' =>

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

接口类: package com.blog.db.dao; import com.blog.util.Pagination; import java.util.List; public interface PublicDao<T> { public void setMapper(Class t); public void setTableName(String tn); public List<T> queryList(Pagination pagination); public

使用EF框架实现增删改查操作

1:添加数据 第二种方式: 2:删除数据 3:修改数据 4:查询数据 查询所有的数据: 查询部分数据 原文地址:http://blog.51cto.com/11871779/2117128

SSM框架+thymeleaf实现基本的增删改查

前言 本文使用了SSM框架.thymeleaf和jquery实现了基本的增删改查. 名词解释 SSM框架:springMVC.spring.mybatis thymeleaf:一个与Velocity.FreeMarker类似的模板引擎 jquery:一个快速.简洁的JavaScript框架 程序结构 本程序框架是用maven建出来的,具体如图: 程序源码 pom.xml <?xml version="1.0" encoding="UTF-8"?> <