SpringBoot创建员工管理系统(六)增删改操作

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


添加员工信息

1. 将添加员工信息改为超链接

<!--添加员工按钮-->
<h2><a class="btn btn-sm btn-success" th:href="@{/toAddPage}">增加员工</a></h2>

2.编写对应的controller

//to员工添加页面
    @GetMapping("/emp")
    public String toAddPage(){
        return "emp/add";
    }

3.添加前端页面;复制list页面,修改即可

bootstrap官网文档 : https://v4.bootcss.com/docs/4.0/components/forms/ , 我们去可以里面找自己喜欢的样式!

<!--新增员工的表单 -->
            <form th:action="@{/addEmp}" method="post">
                <div class="form-group">
                    <label>LastName</label>
                    <input  name="lastName" type="text" class="form-control" placeholder="kuangshen">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input name="email" type="email" class="form-control" placeholder="24736743@qq.com">
                </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">
                        <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">
                        <label class="form-check-label">女</label>
                    </div>
                </div>
 <!--部门,应该从后台查询显示,用户选择-->
                <div class="form-group">
                    <label>department</label>
                    <select class="form-control" name="department.id">
                         <!--each 遍历这个标签-->
                        <option th:each="dept:${department}"th:text="${dept.departmentName}" th:value="${dept.id}">1</option>

                    </select>
                </div>
                <div class="form-group">
                    <label>Birth</label>
                    <input name="birth" type="text" class="form-control" placeholder="kuangstudy">
                </div>
                <button type="submit" class="btn btn-primary">添加</button>
            </form>

4.部门信息下拉框应该选择的是我们提供的数据,所以我们要修改一下前端和后端

EmpController

//toAddPage
    @RequestMapping("/toAddPage")
    public String toAddPage(Model model){
        Collection<Department> department= departmentDao.getDepartments();
        model.addAttribute("department" ,department);
        return "emp/add";
    }

前端页面

<!--部门,应该从后台查询显示,用户选择-->
                <div class="form-group">
                    <label>department</label>
                    <select class="form-control" name="department.id">
                         <!--each 遍历这个标签-->
                        <option th:each="dept:${department}"th:text="${dept.departmentName}" th:value="${dept.id}">1</option>

                    </select>
                </div>

1.修改add页面form表单提交地址和方式

<form th:action="@{/emp}" method="post">

2.编写controller;

//addEmp
    @RequestMapping("/addEmp")
    public String addEmp(Employee employee){
        System.out.println("测试信息:"+employee);
        //保存到数据库
        employeeDao.save(employee);
//回到员工列表,转发,重定向
        return  "redirect:/emplist";
    }

重定向和转发 以及 /的问题?

原理探究 : ThymeleafViewResolver

public static final String REDIRECT_URL_PREFIX = "redirect:";
    public static final String FORWARD_URL_PREFIX = "forward:";

    protected View createView(String viewName, Locale locale) throws Exception {
        if (!this.alwaysProcessRedirectAndForward && !this.canHandle(viewName, locale)) {
            vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
            return null;
        } else {
            String forwardUrl;
            if (viewName.startsWith("redirect:")) {
                vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
                forwardUrl = viewName.substring("redirect:".length(), viewName.length());
                RedirectView view = new RedirectView(forwardUrl, this.isRedirectContextRelative(), this.isRedirectHttp10Compatible());
                return (View)this.getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);
            } else if (viewName.startsWith("forward:")) {
                vrlogger.trace("[THYMELEAF] View \"{}\" is a forward, and will not be handled directly by ThymeleafViewResolver.", viewName);
                forwardUrl = viewName.substring("forward:".length(), viewName.length());
                return new InternalResourceView(forwardUrl);
            } else if (this.alwaysProcessRedirectAndForward && !this.canHandle(viewName, locale)) {
                vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
                return null;
            } else {
                vrlogger.trace("[THYMELEAF] View {} will be handled by ThymeleafViewResolver and a {} instance will be created for it", viewName, this.getViewClass().getSimpleName());
                return this.loadView(viewName, locale);
            }
        }
    }

我们要接收前端传过来的属性,将它封装成为对象!首先需要将前端页面空间的name属性编写完毕!

编写controller接收调试打印

//addEmp
    @RequestMapping("/addEmp")
    public String addEmp(Employee employee){
        System.out.println("测试信息:"+employee);
        //保存到数据库
        employeeDao.save(employee);
//回到员工列表,转发,重定向
        return  "redirect:/emplist";
    }

此时的前端页面如下图所示:

SpringBoot创建员工管理系统(六)增删改操作_前端页面

注册完成后,页面跳转显示正常,但是时间格式为

SpringBoot创建员工管理系统(六)增删改操作_ci_02

当提交为下图是就会报400错

SpringBoot创建员工管理系统(六)增删改操作_ci_03

设置时间格式,使其可以为默认的格式:

在webmvc的自动配置文件;找到一个日期格式化的方法,我们可以看一下

@Bean
        public FormattingConversionService mvcConversionService() {
            WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());
            this.addFormatters(conversionService);
            return conversionService;
        }

调用了 getDateFormat 方法;

public String getDateFormat() {
        return this.dateFormat;
    }

这个在配置类中,所以我们可以自定义的去修改这个时间格式化问题,我们在我们的配置文件中修改一下;

spring.mvc.date-format=yyyy-MM-dd

这样时间格式设置就完成了;

员工修改功能

我们要实现员工修改功能,需要实现两步;

1. 点击修改按钮,去到编辑页面,我们可以直接使用添加员工的页面实现

2.显示原数据,修改完毕后跳回列表页面!

我们去实现一下:首先修改跳转链接的位置;

<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>

编写对应的controller

//跳转到修改页面
    @RequestMapping("/update/{id}")
    public String update (@PathVariable("id")Integer id,Model model){
        System.out.println("测试信息--修改的员工id :"+id);
        //根据id查询用户数据
        Employee employee = employeeDao.get(id);
        //将员工数据返回到前端
        model.addAttribute("emp",employee);
        Collection<Department> department= departmentDao.getDepartments();
        model.addAttribute("department" ,department);
        return "emp/update";
    }

将添加页面(add)复制一份,改为update页面,在修改页面,在后台显示查询数据

<!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>员工修改</title>
    <!-- Bootstrap core CSS -->
    <link href="asserts/css/bootstrap.min.css" rel="stylesheet"
          th:href="@{/asserts/css/bootstrap.min.css}">

    <!-- Custom styles for this template -->
    <link href="asserts/css/dashboard.css" rel="stylesheet"
          th:href="@{/asserts/css/dashboard.css}">
    <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>
<!--使用提取的模板 "~{templatename::selector}"-->
<div th:insert="~{commons/bar::topbar}"></div>

<div class="container-fluid">
    <div class="row">
        <!--侧边栏-->
        <div th:insert="~{commons/bar::sidebar(activeUrl='emps.html')}"></div>

        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
            <h2>修改员工信息</h2>
              <!--修改员工的表单 -->
            <form th:action="@{/addEmp}" method="post">
                <div class="form-group">
                    <label>LastName</label>
                    <input  name="lastName" type="text" class="form-control" placeholder="kuangshen"
                    th:value="${emp.lastName}">

                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input name="email" type="email" class="form-control" placeholder="24736743@qq.com"
                           th:value="${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.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.gender==0}">
                        <label class="form-check-label">女</label>
                    </div>
                </div>
 <!--部门,应该从后台查询显示,用户选择-->
                <div class="form-group">
                    <label>department</label>
                    <select class="form-control" name="department.id">
                         <!--each 遍历这个标签-->
                        <!--从后面取出数据,选中要修改的部门信息-->
                        <option th:selected="${emp.id==emp.department.id}" th:each="dept:${department}"th:text="${dept.departmentName}" th:value="${dept.id}">1</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Birth</label>
                    <input name="birth" th:value="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm:ss')}" type="text" class="form-control" placeholder="">
                </div>
                <button type="submit" class="btn btn-primary">更新</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"></script>
<script type="text/javascript" src="asserts/js/popper.min.js"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js"></script>

<!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js"></script>
<script>
    feather.replace()
</script>

<!-- Graphs -->
<script type="text/javascript" src="asserts/js/Chart.min.js"></script>
<script>
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            datasets: [{
                data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
                lineTension: 0,
                backgroundColor: 'transparent',
                borderColor: '#007bff',
                borderWidth: 4,
                pointBackgroundColor: '#007bff'
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: false
                    }
                }]
            },
            legend: {
                display: false,
            }
        }
    });
</script>

</body>

</html>

测试,回显修改完成;

修改表单提交的地址:

<form th:action="@{/updateEmp}" method="post">

设置修改保存编写对应的controller

//处理修改的请求
    @PostMapping("/updateEmp")
    public String updateEmp (Employee employee){
        //保存到数据中
        employeeDao.save(employee);
        //回到员工列表,转发,重定向
        return  "redirect:/emplist";
    }

发现页面提交的没有id;我们在前端加一个隐藏域,提交id;

<!--隐藏域,保存要修改的员工-->
      <input type="hidden" name="id" th:value="${emp.id}">

测试,修改设置成功;

删除功能

list页面,编写提交地址

<a class="btn btn-sm btn-danger" th:href="@{/delEmp/}+${emp.id}">删除</a>

编写Controller

//删除员工
    @RequestMapping("/deleteEmp/{id}")
    public  String deleteEmp(@PathVariable("id")Integer id){
        //删除员工
        employeeDao.delete(id);
        //回到员工列表,转发,重定向
        return  "redirect:/emplist";
    }

测试完成;

404问题

在templates下面建立一个error目录,将错误页面放进去就可以了;

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring