當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringMVC自动将请求参数和入参对象的属性进行一一绑定;要求请求参数的名字和javaBean入参的对象里面的属性名是一样的||员工的增删改查案例
生活随笔
收集整理的這篇文章主要介紹了
SpringMVC自动将请求参数和入参对象的属性进行一一绑定;要求请求参数的名字和javaBean入参的对象里面的属性名是一样的||员工的增删改查案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SpringMVC自動將請求參數和入參對象的屬性進行一一綁定;要求請求參數的名字和javaBean入參的對象里面的屬性名是一樣的
1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自動配置好的)
2、頁面創建一個post表單
3、創建一個input項,name="_method";值就是我們指定的請求方式
Department.java
package com.atguigu.springboot.entities;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.springboot.entities;import java.util.Date;public class Employee {private Integer id;private String lastName;private String email;//1 male, 0 femaleprivate Integer gender;private Department department;private Date birth;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 Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}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;this.birth = new Date();}public Employee() {}@Overridepublic String toString() {return "Employee{" +"id=" + id +", lastName='" + lastName + '\'' +", email='" + email + '\'' +", gender=" + gender +", department=" + department +", birth=" + birth +'}';} }DepartmentDao.java
package com.atguigu.springboot.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import com.atguigu.springboot.entities.Department; import org.springframework.stereotype.Repository;@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);}}EmployeeDao.java
package com.atguigu.springboot.dao;import java.util.Collection; import java.util.HashMap; import java.util.Map;import com.atguigu.springboot.entities.Department; import com.atguigu.springboot.entities.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;@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")));}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);} }EmployeeController.java
package com.atguigu.springboot.controller;import com.atguigu.springboot.dao.DepartmentDao; import com.atguigu.springboot.dao.EmployeeDao; import com.atguigu.springboot.entities.Department; import com.atguigu.springboot.entities.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*;import java.util.Collection;@Controller public class EmployeeController {@AutowiredEmployeeDao employeeDao;@AutowiredDepartmentDao departmentDao;//查詢所有員工返回列表頁面@GetMapping("/emps")public String list(Model model){Collection<Employee> employees = employeeDao.getAll();//放在請求域中model.addAttribute("emps",employees);// thymeleaf默認就會拼串// classpath:/templates/xxxx.htmlreturn "emp/list";}//來到員工添加頁面@GetMapping("/emp")public String toAddPage(Model model){//來到添加頁面,查出所有的部門,在頁面顯示Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("depts",departments);return "emp/add";}//員工添加//SpringMVC自動將請求參數和入參對象的屬性進行一一綁定;要求請求參數的名字和javaBean入參的對象里面的屬性名是一樣的@PostMapping("/emp")public String addEmp(Employee employee){//來到員工列表頁面System.out.println("保存的員工信息:"+employee);//保存員工employeeDao.save(employee);// redirect: 表示重定向到一個地址 /代表當前項目路徑// forward: 表示轉發到一個地址return "redirect:/emps";}//來到修改頁面,查出當前員工,在頁面回顯@GetMapping("/emp/{id}")public String toEditPage(@PathVariable("id") Integer id,Model model){Employee employee = employeeDao.get(id);model.addAttribute("emp",employee);//頁面要顯示所有的部門列表Collection<Department> departments = departmentDao.getDepartments();model.addAttribute("depts",departments);//回到修改頁面(add是一個修改添加二合一的頁面);return "emp/add";}//員工修改;需要提交員工id;@PutMapping("/emp")public String updateEmployee(Employee employee){System.out.println("修改的員工數據:"+employee);employeeDao.save(employee);return "redirect:/emps";}//員工刪除@DeleteMapping("/emp/{id}")public String deleteEmployee(@PathVariable("id") Integer id){employeeDao.delete(id);return "redirect:/emps";}}list.html
<!DOCTYPE html> <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ --> <html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><title>Dashboard Template for Bootstrap</title><!-- Bootstrap core CSS --><link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"><!-- Custom styles for this template --><link href="asserts/css/dashboard.css" th:href="@{/asserts/css/dashboard.css}" rel="stylesheet"><style type="text/css">/* Chart.js */@-webkit-keyframes chartjs-render-animation {from {opacity: 0.99}to {opacity: 1}}@keyframes chartjs-render-animation {from {opacity: 0.99}to {opacity: 1}}.chartjs-render-monitor {-webkit-animation: chartjs-render-animation 0.001s;animation: chartjs-render-animation 0.001s;}</style></head><body><!--引入抽取的topbar--><!--模板名:會使用thymeleaf的前后綴配置規則進行解析--><div th:replace="commons/bar::topbar"></div><div class="container-fluid"><div class="row"><!--引入側邊欄--><div th:replace="commons/bar::#sidebar(activeUri='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><h2><a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">員工添加</a></h2><div class="table-responsive"><table class="table table-striped table-sm"><thead><tr><th>#</th><th>lastName</th><th>email</th><th>gender</th><th>department</th><th>birth</th><th>操作</th></tr></thead><tbody><tr th:each="emp:${emps}"><td th:text="${emp.id}"></td><td>[[${emp.lastName}]]</td><td th:text="${emp.email}"></td><td th:text="${emp.gender}==0?'女':'男'"></td><td th:text="${emp.department.departmentName}"></td><td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td><td><a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">修改</a><button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">刪除</button></td></tr></tbody></table></div></main><form id="deleteEmpForm" method="post"><input type="hidden" name="_method" value="delete"/></form></div></div><!-- Bootstrap core JavaScript================================================== --><!-- Placed at the end of the document so the pages load faster --><script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script><script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script><script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script><!-- Icons --><script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script><script>feather.replace()</script><script>$(".deleteBtn").click(function(){//刪除當前員工的$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();return false;});</script></body> </html>add.html
<!DOCTYPE html> <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ --> <html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><title>Dashboard Template for Bootstrap</title><!-- Bootstrap core CSS --><link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"><!-- Custom styles for this template --><link href="asserts/css/dashboard.css" th:href="@{/asserts/css/dashboard.css}" rel="stylesheet"><style type="text/css">/* Chart.js */@-webkit-keyframes chartjs-render-animation {from {opacity: 0.99}to {opacity: 1}}@keyframes chartjs-render-animation {from {opacity: 0.99}to {opacity: 1}}.chartjs-render-monitor {-webkit-animation: chartjs-render-animation 0.001s;animation: chartjs-render-animation 0.001s;}</style></head><body><!--引入抽取的topbar--><!--模板名:會使用thymeleaf的前后綴配置規則進行解析--><div th:replace="commons/bar::topbar"></div><div class="container-fluid"><div class="row"><!--引入側邊欄--><div th:replace="commons/bar::#sidebar(activeUri='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><!--需要區分是員工修改還是添加;--><form th:action="@{/emp}" method="post"><!--發送put請求修改員工數據--><!--1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自動配置好的)2、頁面創建一個post表單3、創建一個input項,name="_method";值就是我們指定的請求方式--><input type="hidden" name="_method" value="put" th:if="${emp!=null}"/><input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}"><div class="form-group"><label>LastName</label><input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${emp.lastName}"></div><div class="form-group"><label>Email</label><input name="email" type="email" class="form-control" placeholder="zhangsan@atguigu.com" th:value="${emp!=null}?${emp.email}"></div><div class="form-group"><label>Gender</label><br/><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><!--提交的是部門的id--><select class="form-control" name="department.id"><option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option></select></div><div class="form-group"><label>Birth</label><input name="birth" type="text" class="form-control" placeholder="zhangsan" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></div><button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button></form></main></div></div><!-- Bootstrap core JavaScript================================================== --><!-- Placed at the end of the document so the pages load faster --><script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script><script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script><script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script><!-- Icons --><script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script><script>feather.replace()</script></body></html>http://localhost:8083/crud/emps?
http://localhost:8083/crud/emp
http://localhost:8083/crud/emp/1001
總結
以上是生活随笔為你收集整理的SpringMVC自动将请求参数和入参对象的属性进行一一绑定;要求请求参数的名字和javaBean入参的对象里面的属性名是一样的||员工的增删改查案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: thymeleaf公共页面元素抽取 ||
- 下一篇: 案例:简单计算器|| 属性绑定||v-m