當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringMVC-RestfulCRUD || 员工信息表增删改查操作的具体实现
生活随笔
收集整理的這篇文章主要介紹了
SpringMVC-RestfulCRUD || 员工信息表增删改查操作的具体实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
SpringMVC-RestfulCRUD
利用SpringMVC做一個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------控制器查詢所有員工------放在請求域中-----轉(zhuǎn)發(fā)到list頁面展示
? ? ?員工添加:
? ? ? ? ? 在list頁面點擊“”員工添加“”----(查詢出所有的部門信息要展示在頁面)----來到添加頁面(add.jsp)--------輸入員工數(shù)據(jù)--------點擊保存(/emp )------處理器收到員工保存請求(保存員工)--------保存完成以后還是來到列表頁面;
員工列表展示?
員工添加
原生的form表單
用了表單標(biāo)簽的頁面可能會報這個錯誤;
請求域中沒有一個command類型的對象;
來到頁面之前一定要給請求域中放這個對象;
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單獨查出部門信息設(shè)置到員工對象中,頁面提交的只需要提交部門的idemployee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));employees.put(employee.getId(), employee);}/*** 查詢所有員工* @return*/public Collection<Employee> getAll(){return employees.values();}/*** 按照id查詢某個員工* @param id* @return*/public Employee get(Integer id){return employees.get(id);}/*** 刪除某個員工* @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文件的請求是交給tomcat處理的http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js --><!-- 告訴SpringMVC,自己映射的請求就自己處理,不能處理的請求直接交給tomcat --><!-- 靜態(tài)資源能訪問,動態(tài)映射的請求就不行 --><mvc:default-servlet-handler/><!-- springmvc可以保證動態(tài)請求和靜態(tài)請求都能訪問 --><mvc:annotation-driven></mvc:annotation-driven></beans>index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!-- 訪問項目就要展示員工列表頁面 --> <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、放在請求域中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);// 返回列表頁面;重定向到查詢所有員工的請求return "redirect:/emps";}/*** 去員工添加頁面,去頁面之前需要查出所有部門信息,進(jìn)行展示的* * @return*/@RequestMapping("/toaddpage")public String toAddPage(Model model) {// 1、先查出所有部門Collection<Department> departments = departmentDao.getDepartments();// 2、放在請求域中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:這個表單的所有內(nèi)容顯示綁定的是請求域中 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: 男:<form:radiobutton path="gender" value="1"/> 女:<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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用选择器语法查找元素——
- 下一篇: 配置文件加载位置||外部配置加载顺序||