SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查

简介: 这篇文章通过一个具体的项目案例,详细讲解了如何使用SpringMVC、Thymeleaf、Bootstrap以及RESTful风格接口来实现员工信息的增删改查功能。文章提供了项目结构、配置文件、控制器、数据访问对象、实体类和前端页面的完整源码,并展示了实现效果的截图。项目的目的是锻炼使用RESTful风格的接口开发,虽然数据是假数据并未连接数据库,但提供了一个很好的实践机会。文章最后强调了这一章节主要是为了练习RESTful,其他方面暂不考虑。

这篇的主要目的是锻炼使用Result风格的接口开发。数据是假数据(并未真正连接到数据库)、页面使用BootStrap大致构建一下(不至于那么丑)

项目地址:F:\workspace\SpringMVC代码\SpringMVC-rest

项目的搭建过程、如何配置Tomcat过程略、改专栏系列之前有些。此处不做赘述

1、项目结构

在这里插入图片描述

2、源码

2.1、web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--配置过滤器编码-->
    <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>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <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>

    <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
        <init-param>
            <!-- contextConfigLocation为固定值 -->
            <param-name>contextConfigLocation</param-name>
            <!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的
            src/main/resources -->
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <!--
        作为框架的核心组件,在启动过程中有大量的初始化操作要做
        而这些操作放在第一次请求时才执行会严重影响访问速度
        因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <!--
        设置springMVC的核心控制器所能处理的请求的请求路径
        /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
        但是/不能匹配.jsp请求路径的请求
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

2.2 springMVC.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描组件-->
    <context:component-scan base-package="com.zyz.mvc"></context:component-scan>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver"
          class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--配置视图控制器-->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <mvc:view-controller path="/addEmployee" view-name="employee_add"></mvc:view-controller>

    <!--开放对静态资源的访问-->
    <mvc:default-servlet-handler/>

    <!--开启mvc的注解驱动-->
    <mvc:annotation-driven/>

</beans>

2.3 EmployeeController.java

package com.zyz.mvc.controller;

import com.zyz.mvc.dao.EmployeeDao;
import com.zyz.mvc.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

/**
 * @author zyz
 * @version 1.0
 * @data 2022/11/28 22:00
 * @Description:
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    /**
     * 查询所有员工信息
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    public String getAllEmployee(Model model){
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList",employeeList);
        return "employee_list";
    }

    /**
     * 删除员工信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id") Integer id ){
        employeeDao.delete(id);
        return "redirect:/employee";
    }

    /**
     * 添加用户信息
     * @param employee
     * @return
     */
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String addEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

    /**
     * 跳转修改员工信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
    public String toUpdateEmployee(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee",employee);
        return "employee_update";
    }

    /**
     * 修改用户信息
     * @param employee
     * @return
     */
    @RequestMapping(value = "/employee",method = RequestMethod.PUT)
    public String upDateEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

}

2.4 EmployeeDao.java

假数据模拟

package com.zyz.mvc.dao;

import com.zyz.mvc.pojo.Employee;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zyz
 * @version 1.0
 * @data 2022/11/28 21:56
 * @Description:
 */
@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", "aa@163.com", 1));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 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.5 Employee.java

实体类 使用Lombok

package com.zyz.mvc.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @author zyz
 * @version 1.0
 * @data 2022/11/28 21:54
 * @Description:
 */
@Data
@AllArgsConstructor
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;

}

2.6 employee_list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>员工信息</title>
    <style type="text/css">
        a {
            text-decoration: none;
        }
    </style>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>员工信息----------显示所有员工信息</small>
                </h1>
            </div>
        </div>
    </div>

    <div class="row ">
        <div class="col-md-4 column">
            <a class="btn btn-primary btn-sm" th:href="@{/addEmployee}">添加员工</a>

        </div>

        <div class="col-md-4 column">

        </div>

    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table id="mydataTable" class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>邮箱</th>
                    <th>性别</th>
                    <th colspan="2">操作</th>
                </tr>
                </thead>
                <!--查询用户处理-->
                <tbody>
                <tr th:each="employee : ${employeeList}">
                    <td th:text="${employee.id}"></td>
                    <td th:text="${employee.lastName}"></td>
                    <td th:text="${employee.email}"></td>
                    <td>
                        <div th:switch="${employee.gender}">
                            <span th:case="1">男</span>
                            <span th:case="0">女</span>
                        </div>
                    </td>
                    <td>
                        <a class="btn btn-danger btn-xs" @click="deleteEmployee"
                           th:href="@{'/employee/'+${employee.id}}">删除</a>
                        <a class="btn btn-primary btn-xs" th:href="@{'/employee/'+${employee.id}}">修改</a>

                    </td>

                </tr>
                </tbody>
            </table>
        </div>
    </div>

</div>

<form id="deleteForm" method="post">
    <input type="hidden" name="_method" value="DELETE">
</form>

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
    var vue = new Vue({
        el: "#mydataTable",
        methods: {
            deleteEmployee: function (event) {
                var deleteForm = document.getElementById("deleteForm");
                deleteForm.action = event.target.href;
                deleteForm.submit();
                event.preventDefault();
            }
        }

    })
</script>

</body>
</html>

2.6 employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>添加员工</small>
                </h1>
            </div>
        </div>
    </div>
    <form th:action="@{/employee}" method="post">

        <div class="form-group">
            <label>姓名</label>
            <input type="text" class="form-control" name="lastName">
        </div>
        <div class="form-group">
            <label>邮箱</label>
            <input type="text" class="form-control" name="email">
        </div>
        <div class="form-group">
            <label>性别 </label>
            <input type="radio" name="gender" value="1" checked>男
            <input type="radio" name="gender" value="0">女
        </div>
        <input type="submit" class="btn btn-default" value="添加">

    </form>
</div>
</div>

</body>
</html>

2.6 employee_update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改信息</small>
                </h1>
            </div>
        </div>
    </div>
    <form th:action="@{/employee}" method="post">
        <input type="hidden" name="_method" value="put">
        <input type="hidden" name="id" th:value="${employee.id}">
        <div class="form-group">
            <label>姓名</label>
            <input type="text" class="form-control" name="lastName" th:value="${employee.lastName}">
        </div>
        <div class="form-group">
            <label>邮箱</label>
            <input type="text" class="form-control" name="email" th:value="${employee.email}">
        </div>
        <div class="form-group">
            <label >性别 </label>
            <input type="radio" name="gender" value="1" th:field="${employee.gender}">男
            <input type="radio" name="gender" value="0" th:field="${employee.gender}">女
        </div>
        <input type="submit" class="btn btn-default" value="保存">

    </form>
</div>
</div>

</body>
</html>

2.6 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
    <style type="text/css">
        a{
            text-decoration: none;
            color: black;
            font-size: 18px;
        }
        h3{

            width: 180px;
            height: 38px;
            margin:100px auto;
            text-align: center;
            line-height: 38px;
            background: deepskyblue;
            border-radius: 5px;

        }

    </style>
</head>
<body>

<h3>
    <a th:href="@{/employee}">查看所有员工信息</a><br>
</h3>
<h3>
    <a th:href="@{/addEmployee}">添加员工</a>
</h3>

</body>
</html>

3、实现的效果

3.1 首页

在这里插入图片描述

3.2 全部员工信息

在这里插入图片描述

3.3 添加员工

在这里插入图片描述

3.4 删除员工

在这里插入图片描述

3.5 修改信息

在这里插入图片描述
在这里插入图片描述

4、后语

这一章节主要练习RESTful、其它的暂不考虑。。。。。。

相关文章
|
9月前
|
JSON 前端开发 Java
【SpringMVC】基础入门实战(3)
SpringMVC获取Header,返回静态页面,返回数据(Controller),返回数据@ResponseBody,返回HTML代码片段,返回JSON,设置状态码,设置Header
|
10月前
Bootstrap5 信息提示框3
提示框动画使用 `.fade` 和 `.show` 类来实现关闭时的淡入淡出效果。示例代码:`&lt;div class=&quot;alert alert-danger alert-dismissible fade show&quot;&gt;`
|
Java 数据库连接 Spring
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
文章是关于Spring、SpringMVC、Mybatis三个后端框架的超详细入门教程,包括基础知识讲解、代码案例及SSM框架整合的实战应用,旨在帮助读者全面理解并掌握这些框架的使用。
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
|
10月前
Bootstrap5 信息提示框2
通过在提示框的 `div` 中添加 `.alert-dismissible` 类,并在关闭按钮上添加 `class=&quot;btn-close&quot;` 和 `data-bs-dismiss=&quot;alert&quot;`,可以实现提示框的关闭功能。
|
10月前
|
前端开发
Bootstrap5 信息提示框1
Bootstrap 5 提供了简单易用的信息提示框功能。通过 `.alert` 类结合不同的状态类(如 `.alert-success`、`.alert-info` 等),可以创建各种样式的信息提示框。此外,还可以在提示框中添加带有 `alert-link` 类的链接,使其颜色与提示框一致。例如:
|
11月前
|
存储 数据库连接 API
构建RESTful API:使用FastAPI实现高效的增删改查操作
构建RESTful API:使用FastAPI实现高效的增删改查操作
405 0
SpringMVC入门到实战------十二、异常处理器
这篇文章介绍了SpringMVC中拦截器的使用,包括拦截器的配置、拦截器的三个抽象方法`preHandle`、`postHandle`和`afterCompletion`的作用,以及多个拦截器的执行顺序和规则。
|
设计模式 前端开发 JavaScript
Spring MVC(一)【什么是Spring MVC】
Spring MVC(一)【什么是Spring MVC】
|
前端开发 Java 关系型数据库
基于ssm框架旅游网旅游社交平台前后台管理系统(spring+springmvc+mybatis+maven+tomcat+html)
基于ssm框架旅游网旅游社交平台前后台管理系统(spring+springmvc+mybatis+maven+tomcat+html)
193 0
|
前端开发 Java Go
Spring MVC 和 Spring Boot 的区别
Spring MVC 和 Spring Boot 的区别
353 0