SpringBoot-18-模块开发-员工添加操作

在人生的道路上,不管是潇洒走一回,或者是千山独行,皆须是自己想走的路,虽然,有的人并不是很快就能找到自己的方向和道路,不过,只要坚持到底,我相信,就一定可以找到自己的路,只要找到路,就不必怕路途遥远了。

导读:本篇文章讲解 SpringBoot-18-模块开发-员工添加操作,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

5.6.6 员工添加
  • 添加按钮,在列表页emps/list.html添加按钮,注意这个链接用的是get请求,对比后面表单提交时的同post请求,来提现rest风格
<h2><a class="btn btn-sm btn-success" th:href="@{/empls/toAddPage}" th:text="添加员工"></a></h2>

  • 跳转到添加页面emps/addPage.html
@GetMapping("/toAddPage")
public String toAddPage(Model model){
    Collection<Department> departments = departmentDao.getDepartments();
    model.addAttribute("departments",departments);
    return "emps/addPage";
}
  • 注意department.id的设置,我们controller.接收的是一个EmpLoyee,而我们提交的是department对象其中的一个属性,所以我们的name需要对应的是department对象其中的一个属性
<!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 th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link 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>
<div th:replace="~{commons/commons.html::topBar}"></div>

<div class="container-fluid">
    <div class="row">
        <div th:replace="~{commons/commons.html::sidebar(active='emps-list')}"></div>

        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
            <h2>Section title</h2>
            <form th:action="@{/empls/toAddPage}" method="post">
                <div class="form-group">
                    <label>LastName</label>
                    <input type="text" name="lastName" class="form-control" placeholder="名字">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" placeholder="1176244270@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>
                    <!--我们controller.接收的是一个EmpLoyee,而我们提交的是其中的一个属性,所以我们需要对应的是其中的一个属性-->
                    <select class="form-control" name="department.id">

                        <option th:each="item:${departments}" th:text="${item.departmentName}" th:value="${item.id}"></option>

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

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}" ></script>
<script type="text/javascript" th:src="@{/asserts/js/popper.min.js}" ></script>
<script type="text/javascript" th:src="@{/asserts/js/bootstrap.min.js}" ></script>
<!-- Icons -->
<script type="text/javascript" th:src="@{/asserts/js/feather.min.js}" ></script>
<script>
    feather.replace()
</script>

<!-- Graphs -->
<script type="text/javascript" th: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>
  • 添加员工成功,这个路径和跳转添加路径一致,只是请求方式不同
@PostMapping("/toAddPage")
public String toAdd(Employee employee){
    employeeDao.saveEmployee(employee);
    return "redirect:/empls/toList";
}
  • 注意视图解析器是用的ThymeleafViewResolver的
@Override
    protected View createView(final String viewName, final Locale locale) throws Exception {
        // First possible call to check "viewNames": before processing redirects and forwards
        if (!this.alwaysProcessRedirectAndForward && !canHandle(viewName, locale)) {
            vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
            return null;
        }
        // Process redirects (HTTP redirects)
        if (viewName.startsWith(REDIRECT_URL_PREFIX)) {
            vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
            final String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length(), viewName.length());
            final RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible());
            return (View) getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, REDIRECT_URL_PREFIX);
        }
        // Process forwards (to JSP resources)
        if (viewName.startsWith(FORWARD_URL_PREFIX)) {
            // The "forward:" prefix will actually create a Servlet/JSP view, and that's precisely its aim per the Spring
            // documentation. See http://docs.spring.io/spring-framework/docs/4.2.4.RELEASE/spring-framework-reference/html/mvc.html#mvc-redirecting-forward-prefix
            vrlogger.trace("[THYMELEAF] View \"{}\" is a forward, and will not be handled directly by ThymeleafViewResolver.", viewName);
            final String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length(), viewName.length());
            return new InternalResourceView(forwardUrl);
        }
        // Second possible call to check "viewNames": after processing redirects and forwards
        if (this.alwaysProcessRedirectAndForward && !canHandle(viewName, locale)) {
            vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
            return null;
        }
        vrlogger.trace("[THYMELEAF] View {} will be handled by ThymeleafViewResolver and a " +
                        "{} instance will be created for it", viewName, getViewClass().getSimpleName());
        return loadView(viewName, locale);
    }
  • 在ThymeleafViewResolver的视图解析器中定义了重定向和转发的规则,但我们也可以定义自己的视图解析器,

  • 返回首页

@RequestMapping("/toList")
public String toList(Model model){
    Collection<Employee> employees = employeeDao.getEmployees();
    model.addAttribute("empls",employees);
    return "emps/list";
}
  • 另外springboot默认的时间格式是spring:mvc:format:date: yyyy/MM/dd,参考源码WebMvcProperties中的属性可知。但一般提交表单用的是yyyy-MM-dd,需要自定义设置下
public class WebMvcProperties {
/**
 * Date format to use, for example 'dd/MM/yyyy'.
 */
private String date;
}
spring:
  mvc:
    format:
      date-time: yyyy-MM-dd HH:mm:ss:SSS
      date: yyyy-MM-dd
  • 测试添加员工操作
    在这里插入图片描述
  • 员工添加页面
    在这里插入图片描述
  • 结果
    在这里插入图片描述

下一篇:SpringBoot-19-模块开发-员工修改/删除

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/123853.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!