日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringMVC-RestfulCRUD || 员工信息表增删改查操作的具体实现

發(fā)布時(shí)間:2025/4/16 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringMVC-RestfulCRUD || 员工信息表增删改查操作的具体实现 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

SpringMVC-RestfulCRUD

利用SpringMVC做一個(gè)CRUD(增刪改查)符合Rest風(fēng)格的;

C:Create:創(chuàng)建

R:Retrieve:查詢

U:Update:更新

D:Delete:刪除

數(shù)據(jù)庫:保存數(shù)據(jù);

使用Map,List保存數(shù)據(jù)之類




員工列表展示;查詢所有員工;

? ? ?員工列表展示:訪問index.jsp----直接發(fā)送/emps------控制器查詢所有員工------放在請(qǐng)求域中-----轉(zhuǎn)發(fā)到list頁面展示

? ? ?員工添加:

? ? ? ? ? 在list頁面點(diǎn)擊“”員工添加“”----(查詢出所有的部門信息要展示在頁面)----來到添加頁面(add.jsp)--------輸入員工數(shù)據(jù)--------點(diǎn)擊保存(/emp )------處理器收到員工保存請(qǐng)求(保存員工)--------保存完成以后還是來到列表頁面;



員工列表展示?



員工添加

原生的form表單




用了表單標(biāo)簽的頁面可能會(huì)報(bào)這個(gè)錯(cuò)誤;

請(qǐng)求域中沒有一個(gè)command類型的對(duì)象;

來到頁面之前一定要給請(qǐng)求域中放這個(gè)對(duì)象;








Department.java

package com.atguigu.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;}@Overridepublic String toString() {return "Department [id=" + id + ", departmentName=" + departmentName + "]";}}

Employee.java

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

DepartmentDao.java

package com.atguigu.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import org.springframework.stereotype.Repository;import com.atguigu.bean.Department;/*** 操作部門的dao*/ @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"));}/*** 返回所有的部門* @return*/public Collection<Department> getDepartments(){return departments.values();}/*** 按照部門id查詢部門* @param id* @return*/public Department getDepartment(Integer id){return departments.get(id);}}

EmployeeDao.java

package com.atguigu.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.bean.Department; import com.atguigu.bean.Employee;/*** EmployeeDao:操作員工*/ @Repository public class EmployeeDao {private static Map<Integer, Employee> employees = null;@Autowiredprivate 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")));}//初始idprivate static Integer initId = 1006;/*** 員工保存/更新二合一方法;* @param employee*/public void save(Employee employee){if(employee.getId() == null){employee.setId(initId++);}//根據(jù)部門id單獨(dú)查出部門信息設(shè)置到員工對(duì)象中,頁面提交的只需要提交部門的idemployee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));employees.put(employee.getId(), employee);}/*** 查詢所有員工* @return*/public Collection<Employee> getAll(){return employees.values();}/*** 按照id查詢某個(gè)員工* @param id* @return*/public Employee get(Integer id){return employees.get(id);}/*** 刪除某個(gè)員工* @param id*/public void delete(Integer id){employees.remove(id);} }

web.xml

<?xml version="1.0" encoding="UTF-8"?> <!--suppress ALL --> <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"><display-name>7.SpringMVC_crud</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><!-- 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><!-- 字符編碼Filter --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 支持Rest風(fēng)格轉(zhuǎn)換的filter --><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>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?> <!--suppress ALL --> <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"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><context:component-scan base-package="com.atguigu"></context:component-scan><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/pages/"></property><property name="suffix" value=".jsp"></property></bean><!-- 默認(rèn)前端控制器是攔截所有資源(除過jsp),js文件就404了;要js文件的請(qǐng)求是交給tomcat處理的http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js --><!-- 告訴SpringMVC,自己映射的請(qǐng)求就自己處理,不能處理的請(qǐng)求直接交給tomcat --><!-- 靜態(tài)資源能訪問,動(dòng)態(tài)映射的請(qǐng)求就不行 --><mvc:default-servlet-handler/><!-- springmvc可以保證動(dòng)態(tài)請(qǐng)求和靜態(tài)請(qǐng)求都能訪問 --><mvc:annotation-driven></mvc:annotation-driven></beans>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!-- 訪問項(xiàng)目就要展示員工列表頁面 --> <jsp:forward page="/emps"></jsp:forward>

EmployeeController.java

package com.atguigu.controller;import java.util.Collection;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.bean.Department; import com.atguigu.bean.Employee; import com.atguigu.dao.DepartmentDao; import com.atguigu.dao.EmployeeDao;@Controller public class EmployeeController {@AutowiredEmployeeDao employeeDao;@AutowiredDepartmentDao departmentDao;/*** 查詢所有員工* * @return*/@RequestMapping("/emps")public String getEmps(Model model) {Collection<Employee> all = employeeDao.getAll();model.addAttribute("emps", all);return "list";}/*** 刪除員工** @return*/@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)public String deleteEmp(@PathVariable("id")Integer id){employeeDao.delete(id);return "redirect:/emps";}/*** 查詢員工,來到修改頁面回顯* * @param id* @param model* @return*/@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)public String getEmp(@PathVariable("id") Integer id, Model model) {// 1、查出員工信息Employee employee = employeeDao.get(id);// 2、放在請(qǐng)求域中model.addAttribute("employee", employee);// 3、繼續(xù)查出部門信息放在隱含模型中Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("depts", departments);return "edit";}@RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT)public String updateEmp(@ModelAttribute("employee")Employee employee/* ,@PathVariable("id")Integer id */) {System.out.println("要修改的員工:" + employee);// xxxx 更新保存二合一;employeeDao.save(employee);return "redirect:/emps";}@ModelAttributepublic void myModelAttribute(@RequestParam(value = "id", required = false) Integer id,Model model) {if (id != null) {Employee employee = employeeDao.get(id);model.addAttribute("employee", employee);}System.out.println("hahha ");}/*** 保存員工* * @param employee* @return*/@RequestMapping(value = "/emp", method = RequestMethod.POST)public String addEmp(Employee employee) {System.out.println("要添加的員工:" + employee);employeeDao.save(employee);// 返回列表頁面;重定向到查詢所有員工的請(qǐng)求return "redirect:/emps";}/*** 去員工添加頁面,去頁面之前需要查出所有部門信息,進(jìn)行展示的* * @return*/@RequestMapping("/toaddpage")public String toAddPage(Model model) {// 1、先查出所有部門Collection<Department> departments = departmentDao.getDepartments();// 2、放在請(qǐng)求域中model.addAttribute("depts", departments);model.addAttribute("employee", new Employee());// 3、去添加頁面return "add";}}

list.jsp

<%@ 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><%pageContext.setAttribute("ctp", request.getContextPath()); %><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title><script type="text/javascript" src="${ctp}/scripts/jquery-1.9.1.min.js"></script></head> <body><h1>員工列表</h1><%-- cellpadding:單元格里面文字到單元格邊框的距離cellspacing:單元格之間的距離--%><table border="1" cellpadding="5" cellspacing="0"><tr><th>ID</th><th>lastName</th><th>email</th><th>gender</th><th>departmentName</th><th>EDIT</th><th>DELETE</th></tr><c:forEach items="${emps}" var="emp"><tr><td>${emp.id}</td><td>${emp.lastName}</td><td>${emp.email}</td><td>${emp.gender==0?"女":"男"}</td><td>${emp.department.departmentName}</td><td><a href="${ctp}/emp/${emp.id}">edit</a></td><td><a href="${ctp}/emp/${emp.id}" class="delBtn">delete</a></td></tr></c:forEach></table><a href="${ctp}/toaddpage">添加員工</a><form id="deleteForm" action="" method="post"><input type="hidden" name="_method" value="DELETE" /> </form><script type="text/javascript">$(function(){$(".delBtn").click(function(){//0、確認(rèn)刪除?//1、改變表單的action指向$("#deleteForm").attr("action",this.href);//2、提交表單$("#deleteForm").submit();return false;});});</script> </body> </html>

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@taglib prefix="form" uri="http://www.springframework.org/tags/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>Insert title here</title> </head> <body> <h1>員工添加</h1><%pageContext.setAttribute("ctp", request.getContextPath()); %> <%--@elvariable id="employee" type=""--%> <form:form action="${ctp}/emp" modelAttribute="employee" method="POST">lastName:<form:input path="lastName"/><br/>email:<form:input path="email"/><br/>gender:<br/>男:<form:radiobutton path="gender" value="1"/><br/>女:<form:radiobutton path="gender" value="0"/><br/>dept:<form:select path="department.id" items="${depts}"itemLabel="departmentName" itemValue="id"></form:select><br/><input type="submit" value="保存"/></form:form></body> </html>

edit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@taglib prefix="form" uri="http://www.springframework.org/tags/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>Insert title here</title> <%pageContext.setAttribute("ctp", request.getContextPath()); %> </head> <body> <h1>員工修改頁面</h1> <!-- modelAttribute:這個(gè)表單的所有內(nèi)容顯示綁定的是請(qǐng)求域中 employee的值--> <form:form action="${ctp}/emp/${employee.id}"modelAttribute="employee" method="post"><input type="hidden" name="_method" value="put"/><input type="hidden" name="id" value="${employee.id }"/>email:<form:input path="email"/><br/>gender:&nbsp;&nbsp;&nbsp;男:<form:radiobutton path="gender" value="1"/>&nbsp;&nbsp;&nbsp;女:<form:radiobutton path="gender" value="0"/><br/>dept:<form:select path="department.id" items="${depts}"itemLabel="departmentName" itemValue="id"></form:select> <br/><input type="submit" value="修改"/></form:form></body> </html>

總結(jié)

以上是生活随笔為你收集整理的SpringMVC-RestfulCRUD || 员工信息表增删改查操作的具体实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。