SpringMVC--RESTful案例

1、准备工作

和传统 CRUD 一样,实现对员工信息的增删改查。

  • 搭建Maven环境

  • 准备实体类

    package com.rest.bean;
    
    public class Employee {
    
       private Integer id;
       private String lastName;
    
       private String email;
       //1 male, 0 female
       private Integer gender;
       
       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 Employee(Integer id, String lastName, String email, Integer gender) {
          super();
          this.id = id;
          this.lastName = lastName;
          this.email = email;
          this.gender = gender;
       }
    
       public Employee() {
       }
    }
    
  • 准备dao模拟数据

    package com.rest.dao;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.atguigu.mvc.bean.Employee;
    import org.springframework.stereotype.Repository;
    
    
    @Repository
    public class EmployeeDao {
    
       private static Map<Integer, Employee> employees = null;
       
       static{
          employees = new HashMap<Integer, Employee>();
    
          employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
          employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
          employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
          employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
          employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
       }
       
       private static Integer initId = 1006;
       
       public void save(Employee employee){
          if(employee.getId() == null){
             employee.setId(initId++);
          }
          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);
       }
    }
    

2、功能清单

功能 URL 地址 请求方式
访问首页√ / GET
查询全部数据√ /employee GET
删除√ /employee/2 DELETE
跳转到添加数据页面√ /toAdd GET
执行保存√ /employee POST
跳转到更新数据页面√ /employee/2 GET
执行更新√ /employee PUT

3、具体功能:访问首页

a>配置view-controller
<mvc:view-controller path="/" view-name="index"/>
b>在templates下创建index.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" >
    <title>Titletitle>
head>
<body>
<h1>首页h1>
<a th:href="@{/employee}">查看员工信息a>
body>
html>

4、具体功能:查询所有员工数据

a>控制器方法
package com.rest.controller;

import com.rest.bean.Employee;
import com.rest.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;

    @RequestMapping(value ="/employee",method = RequestMethod.GET)
    public String getAllEmployee(Model model){
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList",employeeList);
        return "employee_list";
    }
}
b>在templates下创建employee_list.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Employee Infotitle>
    <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
head>
<body>

    <table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
        <tr>
            <th colspan="5">Employee Infoth>
        tr>
        <tr>
            <th>idth>
            <th>lastNameth>
            <th>emailth>
            <th>genderth>
            <th>options(<a th:href="@{/toAdd}">adda>)th>
        tr>
        <tr th:each="employee : ${employeeList}">
            <td th:text="${employee.id}">td>
            <td th:text="${employee.lastName}">td>
            <td th:text="${employee.email}">td>
            <td th:text="${employee.gender}">td>
            <td>
                <a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">deletea>
                <a th:href="@{'/employee/'+${employee.id}}">updatea>
            td>
        tr>
    table>
body>
html>

切记,th:href="@{/employee/${employee.id}}"写法是错的!

但是th:href="@{/employee}+${employee.id}"也是可以的!

thymeleaf语法中,字符串和变量拼接,直接使用竖线,也可以写成如下:

<a th:href="@{|/employee/${employee.id}|}">删除a>

5、具体功能:删除

a>在employee_list.html下添加处理delete请求方式的表单

<form id="delete_form" method="post">
    
    <input type="hidden" name="_method" value="delete"/>
form>
b>删除超链接绑定点击事件

webapp下新建static目录,再建子目录js,引入vue.js

<script type="text/javascript" th:src="@{/static/js/vue.js}">script>

引入static/js文件后,执行两步:

一、在IDEA中依次点击Maven->生命周期->package,不然服务器找不到js文件。

SpringMVC--RESTful案例_第1张图片

二、在springMVC.xml中开放对静态资源的访问


<mvc:default-servlet-handler/>

删除超链接

<a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">deletea>

通过vue处理点击事件

<script type="text/javascript">
    var vue = new Vue({
        el:"#dataTable",
        methods:{
            //event表示当前事件
            deleteEmployee:function (event) {
                //通过id获取表单标签
                var delete_form = document.getElementById("delete_form");
                //将触发事件的超链接的href属性为表单的action属性赋值
                delete_form.action = event.target.href;
                //提交表单
                delete_form.submit();
                //阻止超链接的默认跳转行为
                event.preventDefault();
            }
        }
    });
script>

使用javascript也可以实现:

<script>
function deleteEmployee(event){
 //通过id获取表单标签
 var delete_form = document.getElementById("delete_form");
 //将触发事件的超链接的href属性为表单的action属性赋值
 delete_form.action = event.target.href;
 //提交表单
 delete_form.submit();
 //阻止超链接的默认跳转行为
 event.preventDefault();
}
</script>
c>控制器方法
@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
    employeeDao.delete(id);
    return "redirect:/employee";
}

6、具体功能:跳转到添加数据页面

a>配置view-controller
<mvc:view-controller path="/toAdd" view-name="employee_add">mvc:view-controller>
b>在templates下创建employee_add.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Add Employeetitle>
head>
<body>

<form th:action="@{/employee}" method="post">
    lastName:<input type="text" name="lastName"><br>
    email:<input type="text" name="email"><br>
    gender:<input type="radio" name="gender" value="1">male
    <input type="radio" name="gender" value="0">female<br>
    <input type="submit" value="add"><br>
form>

body>
html>

7、具体功能:执行保存

a>控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

8、具体功能:跳转到更新数据页面

a>修改超链接
<a th:href="@{'/employee/'+${employee.id}}">updatea>
b>控制器方法
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
    Employee employee = employeeDao.get(id);
    model.addAttribute("employee", employee);
    return "employee_update";
}
c>在templates下创建employee_update.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Update Employeetitle>
head>
<body>

<form th:action="@{/employee}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="hidden" name="id" th:value="${employee.id}">
    lastName:<input type="text" name="lastName" th:value="${employee.lastName}"><br>
    email:<input type="text" name="email" th:value="${employee.email}"><br>
    
    gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
    <input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br>
    <input type="submit" value="update"><br>
form>

body>
html>

9、具体功能:执行更新

a>控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
    employeeDao.save(employee);
    return "redirect:/employee";
}

参考自尚硅谷学习视频~

你可能感兴趣的:(Java,Spring,MVC,restful,java,mvc)