目录

介绍

此 Demo 是为了熟悉 Spring Boot 和 thymeleaf 的使用,所以适用于刚接触 Spring Boot 不久的新手,此项目是一个简单的 Web 版的员工 CRUD,项目内容来源于尚硅谷谷粒学院 Spring Boot 核心技术篇,我根据自己的理解,又重新地动手做了一些,其中也发现了一些自己的薄弱点,并针对这些薄弱点进行巩固,以便尽快掌握 Spring Boot。

零、项目素材

restful-crud-experiment

说明:关于链接无效问题,是因为文件、图片等我是上传到 GitHub上的,详情进入我的GitHub

一、 创建 Spring Boot 项目

  • 开发工具:IDEA

  • 创建方式:使用 Spring Initializr 方式创建

  • 项目结构目录示意图:

    1. ├─src
    2. ├─main
    3. ├─java
    4. └─com
    5. └─yunche
    6. └─controller
    7. └─resources
    8. ├─public
    9. ├─static
    10. └─asserts
    11. ├─css
    12. ├─img
    13. └─js
    14. └─templates

二、定制首页

1、修改 pom.xml

添加 jquery webjars 、bootstrap webjars、thymeleaf 依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.1.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yunche</groupId>
  12. <artifactId>springboot-sample-restfulcrud</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot-sample-restfulcrud</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <!--引入 jquery webjars-->
  25. <!--使用时:路径 webjars/jquery/3.3.1/jquery.js-->
  26. <dependency>
  27. <groupId>org.webjars</groupId>
  28. <artifactId>jquery</artifactId>
  29. <version>3.3.1</version>
  30. </dependency>
  31. <!--引入 bootstrap webjars-->
  32. <dependency>
  33. <groupId>org.webjars</groupId>
  34. <artifactId>bootstrap</artifactId>
  35. <version>4.2.1</version>
  36. </dependency>
  37. <!--引入 thymeleaf3-->
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-test</artifactId>
  45. <scope>test</scope>
  46. </dependency>
  47. </dependencies>
  48. <build>
  49. <plugins>
  50. <plugin>
  51. <groupId>org.springframework.boot</groupId>
  52. <artifactId>spring-boot-maven-plugin</artifactId>
  53. </plugin>
  54. </plugins>
  55. </build>
  56. </project>

2、引入相应的本地 css、js 文件

将对应的文件引入到相应的位置

  1. ├─static
  2. └─asserts
  3. ├─css
  4. bootstrap.min.css
  5. dashboard.css
  6. signin.css

  7. ├─img
  8. bootstrap-solid.svg

  9. └─js
  10. bootstrap.min.js
  11. Chart.min.js
  12. feather.min.js
  13. jquery-3.2.1.slim.min.js
  14. popper.min.js

3、编辑 login.html

  1. └─templates
  2. login.html

使用 thymeleaf 对 login.html 完成 css、js 、form 等链接的修改

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  6. <meta name="description" content="">
  7. <meta name="author" content="">
  8. <title>Signin Template for Bootstrap</title>
  9. <!-- Bootstrap core CSS -->
  10. <link href="asserts/css/bootstrap.min.css" rel="stylesheet" th:href="@{/webjars/bootstrap/4.2.1/css/bootstrap.css}">
  11. <!-- Custom styles for this template -->
  12. <link href="asserts/css/signin.css" rel="stylesheet" th:href="@{/asserts/css/signin.css}">
  13. </head>
  14. <body class="text-center">
  15. <form class="form-signin" action="dashboard.html" method="post" th:action="@{/user/login}">
  16. <img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{/asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
  17. <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please Sign In</h1>
  18. <label class="sr-only" th:text="#{login.username}">Username</label>
  19. <input type="text" name="username" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
  20. <label class="sr-only" th:text="#{login.password}">Password</label>
  21. <input type="password" name="password" class="form-control" placeholder="Password" required="" th:placeholder="#{login.password}">
  22. <div class="checkbox mb-3">
  23. <label>
  24. <input type="checkbox" value="remember-me" > [[#{login.remember}]]
  25. </label>
  26. </div>
  27. <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
  28. <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
  29. <a class="btn btn-sm" > 中文 </a>
  30. <a class="btn btn-sm" >English</a>
  31. </form>
  32. </body>
  33. </html>

4、处理对 login 页面请求的映射

  1. ├─config
  2. MyMvcConfig.java

  3. └─controller

扩展 Spring MVC,添加视图控制器,完成我们自己的路径的映射规则

  1. package com.yunche.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  5. /**
  6. * @ClassName: MyMvcConfig
  7. * @Description: 练习:使用 WebMvcConfigurer 扩展 SpringMVC 的功能
  8. * @author: yunche
  9. * @date: 2019/01/01
  10. */
  11. @Configuration
  12. public class MyMvcConfig implements WebMvcConfigurer {
  13. @Override
  14. public void addViewControllers(ViewControllerRegistry registry) {
  15. registry.addViewController("/").setViewName("login");
  16. registry.addViewController("/index.html").setViewName("login");
  17. registry.addViewController("/index").setViewName("login");
  18. }
  19. }

5、国际化登录页面

  • 编写国际化文件

    1. └─resources
    2. application.properties

    3. ├─i18n
    4. login.en_US.properties
    5. login.properties
    6. login.zh_CN.properties
    • login_en_US.properties:

      1. login.btn=Sign In
      2. login.password=Password
      3. login.remember=Remember Me
      4. login.tip=Please Sign In
      5. login.username=Username
    • login.properties:

      1. login.btn=登录
      2. login.password=密码
      3. login.remember=记住我
      4. login.tip=请登录
      5. login.username=用户名
    • login_zh_CN.properties:

      1. login.btn=登录
      2. login.password=密码
      3. login.remember=记住我
      4. login.tip=请登录
      5. login.username=用户名
  • 绑定编写的国际化配置文件到 Message Source

    1. └─resources
    2. application.properties

    application.properties:

    1. spring.messages.basename=i18n.login
  • 实现按钮手动转换语言

    • 国际化有效的原理:

      Locale 对象存储区域信息, 根据 Locale 来自适应语言配置,默认的LocaleResolver就是根据请求头带来的区域信息(Accept-Language)获取 Locale 对象。如果需要手动转换语言只需要手动构造LocaleResolver来自定义生成 Locale 对象的规则。

    • 定制 LocaleResolver:

      1. ├─component
      2. MyLocaleResolver.java

      MyLocaleResolver.java:

      1. package com.yunche.component;
      2. import org.springframework.stereotype.Component;
      3. import org.springframework.web.servlet.LocaleResolver;
      4. import org.thymeleaf.util.StringUtils;
      5. import javax.servlet.http.HttpServletRequest;
      6. import javax.servlet.http.HttpServletResponse;
      7. import java.util.Locale;
      8. /**
      9. * @ClassName: MyLocaleResolver
      10. * @Description:
      11. * @author: yunche
      12. * @date: 2019/01/01
      13. */
      14. @Component
      15. public class MyLocaleResolver implements LocaleResolver {
      16. @Override
      17. public Locale resolveLocale(HttpServletRequest request) {
      18. String l = request.getParameter("l");
      19. Locale locale = Locale.getDefault();
      20. if (!StringUtils.isEmpty(l)) {
      21. String[] split = l.split("_");
      22. //根据 Language、Country 生成 locale
      23. locale = new Locale(split[0], split[1]);
      24. }
      25. return locale;
      26. }
      27. @Override
      28. public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
      29. }
      30. }
    • 将定制的组件加入容器中

      此时默认的 LocaleResolver 将不再生效,将使用我们定制的 LocaleResolver。

      1. ├─config
      2. MyMvcConfig.java

      MyMvcConfig.java:

      1. /**
      2. * 注册定制组件
      3. */
      4. @Bean
      5. public LocaleResolver localeResolver() {
      6. return new MyLocaleResolver();
      7. }
    • 添加相应的链接参数

      login.html:

      1. <a class="btn btn-sm" th:href="@{/index(l='zh_CN')}"> 中文 </a>
      2. <a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>

6、阶段演示效果

三、完成 login 操作

1、添加控制器用于处理请求

  1. package com.yunche.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.util.StringUtils;
  4. import org.springframework.web.bind.annotation.PostMapping;
  5. /**
  6. * @ClassName: LoginController
  7. * @Description:
  8. * @author: yunche
  9. * @date: 2019/01/02
  10. */
  11. @Controller
  12. public class LoginController {
  13. @PostMapping("/user/login")
  14. public String login(String username, String password) {
  15. if ("admin".equals(username) && !StringUtils.isEmpty(password)) {
  16. return "redirect:/main.html";
  17. }
  18. return "login";
  19. }
  20. }

当用户登录成功后,重定向到后台首页。添加对 /main.html 请求的处理:在 MyMvcConfig 下的 addViewControllers 方法中加入:

  1. registry.addViewController("/main.html").setViewName("dashboard");

2、添加后台首页 dashboard.html

  1. └─templates
  2. dashboard.html

dashboard.html:

  1. <!DOCTYPE html>
  2. <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
  3. <html lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  7. <meta name="description" content="">
  8. <meta name="author" content="">
  9. <title>Dashboard Template for Bootstrap</title>
  10. <!-- Bootstrap core CSS -->
  11. <link href="asserts/css/bootstrap.min.css" rel="stylesheet">
  12. <!-- Custom styles for this template -->
  13. <link href="asserts/css/dashboard.css" rel="stylesheet">
  14. <style type="text/css">
  15. /* Chart.js */
  16. @-webkit-keyframes chartjs-render-animation {
  17. from {
  18. opacity: 0.99
  19. }
  20. to {
  21. opacity: 1
  22. }
  23. }
  24. @keyframes chartjs-render-animation {
  25. from {
  26. opacity: 0.99
  27. }
  28. to {
  29. opacity: 1
  30. }
  31. }
  32. .chartjs-render-monitor {
  33. -webkit-animation: chartjs-render-animation 0.001s;
  34. animation: chartjs-render-animation 0.001s;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0">
  40. <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Company name</a>
  41. <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
  42. <ul class="navbar-nav px-3">
  43. <li class="nav-item text-nowrap">
  44. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
  45. </li>
  46. </ul>
  47. </nav>
  48. <div class="container-fluid">
  49. <div class="row">
  50. <nav class="col-md-2 d-none d-md-block bg-light sidebar">
  51. <div class="sidebar-sticky">
  52. <ul class="nav flex-column">
  53. <li class="nav-item">
  54. <a class="nav-link active" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  55. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
  56. <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
  57. <polyline points="9 22 9 12 15 12 15 22"></polyline>
  58. </svg>
  59. Dashboard <span class="sr-only">(current)</span>
  60. </a>
  61. </li>
  62. <li class="nav-item">
  63. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  64. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
  65. <path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
  66. <polyline points="13 2 13 9 20 9"></polyline>
  67. </svg>
  68. Orders
  69. </a>
  70. </li>
  71. <li class="nav-item">
  72. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  73. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
  74. <circle cx="9" cy="21" r="1"></circle>
  75. <circle cx="20" cy="21" r="1"></circle>
  76. <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
  77. </svg>
  78. Products
  79. </a>
  80. </li>
  81. <li class="nav-item">
  82. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  83. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
  84. <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
  85. <circle cx="9" cy="7" r="4"></circle>
  86. <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
  87. <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
  88. </svg>
  89. Customers
  90. </a>
  91. </li>
  92. <li class="nav-item">
  93. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  94. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2">
  95. <line x1="18" y1="20" x2="18" y2="10"></line>
  96. <line x1="12" y1="20" x2="12" y2="4"></line>
  97. <line x1="6" y1="20" x2="6" y2="14"></line>
  98. </svg>
  99. Reports
  100. </a>
  101. </li>
  102. <li class="nav-item">
  103. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  104. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers">
  105. <polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
  106. <polyline points="2 17 12 22 22 17"></polyline>
  107. <polyline points="2 12 12 17 22 12"></polyline>
  108. </svg>
  109. Integrations
  110. </a>
  111. </li>
  112. </ul>
  113. <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
  114. <span>Saved reports</span>
  115. <a class="d-flex align-items-center text-muted" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  116. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
  117. </a>
  118. </h6>
  119. <ul class="nav flex-column mb-2">
  120. <li class="nav-item">
  121. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  122. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  123. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  124. <polyline points="14 2 14 8 20 8"></polyline>
  125. <line x1="16" y1="13" x2="8" y2="13"></line>
  126. <line x1="16" y1="17" x2="8" y2="17"></line>
  127. <polyline points="10 9 9 9 8 9"></polyline>
  128. </svg>
  129. Current month
  130. </a>
  131. </li>
  132. <li class="nav-item">
  133. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  134. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  135. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  136. <polyline points="14 2 14 8 20 8"></polyline>
  137. <line x1="16" y1="13" x2="8" y2="13"></line>
  138. <line x1="16" y1="17" x2="8" y2="17"></line>
  139. <polyline points="10 9 9 9 8 9"></polyline>
  140. </svg>
  141. Last quarter
  142. </a>
  143. </li>
  144. <li class="nav-item">
  145. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  146. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  147. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  148. <polyline points="14 2 14 8 20 8"></polyline>
  149. <line x1="16" y1="13" x2="8" y2="13"></line>
  150. <line x1="16" y1="17" x2="8" y2="17"></line>
  151. <polyline points="10 9 9 9 8 9"></polyline>
  152. </svg>
  153. Social engagement
  154. </a>
  155. </li>
  156. <li class="nav-item">
  157. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  158. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  159. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  160. <polyline points="14 2 14 8 20 8"></polyline>
  161. <line x1="16" y1="13" x2="8" y2="13"></line>
  162. <line x1="16" y1="17" x2="8" y2="17"></line>
  163. <polyline points="10 9 9 9 8 9"></polyline>
  164. </svg>
  165. Year-end sale
  166. </a>
  167. </li>
  168. </ul>
  169. </div>
  170. </nav>
  171. <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  172. <div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;">
  173. <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
  174. <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
  175. </div>
  176. <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
  177. <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
  178. </div>
  179. </div>
  180. <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
  181. <h1 class="h2">Dashboard</h1>
  182. <div class="btn-toolbar mb-2 mb-md-0">
  183. <div class="btn-group mr-2">
  184. <button class="btn btn-sm btn-outline-secondary">Share</button>
  185. <button class="btn btn-sm btn-outline-secondary">Export</button>
  186. </div>
  187. <button class="btn btn-sm btn-outline-secondary dropdown-toggle">
  188. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-calendar"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>
  189. This week
  190. </button>
  191. </div>
  192. </div>
  193. <canvas class="my-4 chartjs-render-monitor" id="myChart" width="1076" height="454" style="display: block; width: 1076px; height: 454px;"></canvas>
  194. </main>
  195. </div>
  196. </div>
  197. <!-- Bootstrap core JavaScript
  198. ================================================== -->
  199. <!-- Placed at the end of the document so the pages load faster -->
  200. <script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" ></script>
  201. <script type="text/javascript" src="asserts/js/popper.min.js" ></script>
  202. <script type="text/javascript" src="asserts/js/bootstrap.min.js" ></script>
  203. <!-- Icons -->
  204. <script type="text/javascript" src="asserts/js/feather.min.js" ></script>
  205. <script>
  206. feather.replace()
  207. </script>
  208. <!-- Graphs -->
  209. <script type="text/javascript" src="asserts/js/Chart.min.js" ></script>
  210. <script>
  211. var ctx = document.getElementById("myChart");
  212. var myChart = new Chart(ctx, {
  213. type: 'line',
  214. data: {
  215. labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  216. datasets: [{
  217. data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
  218. lineTension: 0,
  219. backgroundColor: 'transparent',
  220. borderColor: '#007bff',
  221. borderWidth: 4,
  222. pointBackgroundColor: '#007bff'
  223. }]
  224. },
  225. options: {
  226. scales: {
  227. yAxes: [{
  228. ticks: {
  229. beginAtZero: false
  230. }
  231. }]
  232. },
  233. legend: {
  234. display: false,
  235. }
  236. }
  237. });
  238. </script>
  239. </body>
  240. </html>

3、添加登录错误消息展示

LoginController:

  1. @Controller
  2. public class LoginController {
  3. @PostMapping("/user/login")
  4. public String login(String username, String password, Map<String, Object> map, HttpSession session) {
  5. if ("admin".equals(username) && "123".equals(password)) {
  6. session.setAttribute("user", username);
  7. return "redirect:/main.html";
  8. }
  9. map.put("loginState", "login fail");
  10. return "login";
  11. }
  12. }

login.html:

  1. <!--lead into js-->
  2. <script src="../static/asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}"></script>
  3. <script src="../static/asserts/js/popper.min.js" th:src="@{/asserts/js/popper.min.js}"></script>
  4. <script src="../static/asserts/js/bootstrap.min.js" th:src="@{/asserts/js/bootstrap.min.js}"></script>
  5. ......
  6. <div th:switch="${loginState}">
  7. <div class="alert alert-danger alert-dismissible fade show" role="alert" th:case="'login fail'">
  8. [[#{login.result}]]
  9. <button type="button" class="close" data-dismiss="alert" aria-label="Close">
  10. <span aria-hidden="true">&times;</span>
  11. </button>
  12. </div>
  13. <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}" th:case="*">Please Sign In</h1>
  14. </div>

在国际化文件添加 login.result 及相应的值。

4、定制拦截器

  • LoginHandlerInterceptor:
  1. package com.yunche.component;
  2. import org.springframework.web.servlet.HandlerInterceptor;
  3. import org.springframework.web.servlet.ModelAndView;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. /**
  7. * @ClassName: LoginHandlerInterceptor
  8. * @Description:
  9. * @author: yunche
  10. * @date: 2019/01/03
  11. */
  12. public class LoginHandlerInterceptor implements HandlerInterceptor {
  13. /**
  14. * 目标方法执行前
  15. * @param request
  16. * @param response
  17. * @param handler
  18. * @return
  19. * @throws Exception
  20. */
  21. @Override
  22. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  23. Object user = request.getSession().getAttribute("user");
  24. if (user == null) {
  25. //未登录,返回登录页面
  26. //request.setAttribute("msg", "没有权限请先登录");
  27. request.getRequestDispatcher("/index.html").forward(request, response);
  28. return false;
  29. }
  30. return true;
  31. }
  32. @Override
  33. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  34. }
  35. @Override
  36. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  37. }
  38. }

四、员工的 CRUD

未与数据库进行连接,仅作模拟操作。

1、引入相应的 dao 和 entity 类

  1. ├─dao
  2. DepartmentDao.java
  3. EmployeeDao.java

  4. └─entities
  5. Department.java
  6. Employee.java
  • DepartmentDao.java:

    1. package com.yunche.dao;
    2. import java.util.Collection;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import com.yunche.entities.Department;
    6. import org.springframework.stereotype.Repository;
    7. @Repository
    8. public class DepartmentDao {
    9. private static Map<Integer, Department> departments = null;
    10. static{
    11. departments = new HashMap<Integer, Department>();
    12. departments.put(101, new Department(101, "D-AA"));
    13. departments.put(102, new Department(102, "D-BB"));
    14. departments.put(103, new Department(103, "D-CC"));
    15. departments.put(104, new Department(104, "D-DD"));
    16. departments.put(105, new Department(105, "D-EE"));
    17. }
    18. public Collection<Department> getDepartments(){
    19. return departments.values();
    20. }
    21. public Department getDepartment(Integer id){
    22. return departments.get(id);
    23. }
    24. }
  • EmployeeDao.java:

    1. package com.yunche.dao;
    2. import java.util.Collection;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import com.yunche.entities.Department;
    6. import com.yunche.entities.Employee;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Repository;
    9. @Repository
    10. public class EmployeeDao {
    11. private static Map<Integer, Employee> employees = null;
    12. @Autowired
    13. private DepartmentDao departmentDao;
    14. static{
    15. employees = new HashMap<Integer, Employee>();
    16. employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
    17. employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
    18. employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
    19. employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
    20. employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
    21. }
    22. private static Integer initId = 1006;
    23. public void save(Employee employee){
    24. if(employee.getId() == null){
    25. employee.setId(initId++);
    26. }
    27. employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
    28. employees.put(employee.getId(), employee);
    29. }
    30. public Collection<Employee> getAll(){
    31. return employees.values();
    32. }
    33. public Employee get(Integer id){
    34. return employees.get(id);
    35. }
    36. public void delete(Integer id){
    37. employees.remove(id);
    38. }
    39. }
  • Department.java:

    1. package com.yunche.entities;
    2. public class Department {
    3. private Integer id;
    4. private String departmentName;
    5. public Department() {
    6. }
    7. public Department(int i, String string) {
    8. this.id = i;
    9. this.departmentName = string;
    10. }
    11. public Integer getId() {
    12. return id;
    13. }
    14. public void setId(Integer id) {
    15. this.id = id;
    16. }
    17. public String getDepartmentName() {
    18. return departmentName;
    19. }
    20. public void setDepartmentName(String departmentName) {
    21. this.departmentName = departmentName;
    22. }
    23. @Override
    24. public String toString() {
    25. return "Department [id=" + id + ", departmentName=" + departmentName + "]";
    26. }
    27. }
  • Employee.java:

    1. package com.yunche.entities;
    2. import java.util.Date;
    3. public class Employee {
    4. private Integer id;
    5. private String lastName;
    6. private String email;
    7. //1 male, 0 female
    8. private Integer gender;
    9. private Department department;
    10. private Date birth;
    11. public Integer getId() {
    12. return id;
    13. }
    14. public void setId(Integer id) {
    15. this.id = id;
    16. }
    17. public String getLastName() {
    18. return lastName;
    19. }
    20. public void setLastName(String lastName) {
    21. this.lastName = lastName;
    22. }
    23. public String getEmail() {
    24. return email;
    25. }
    26. public void setEmail(String email) {
    27. this.email = email;
    28. }
    29. public Integer getGender() {
    30. return gender;
    31. }
    32. public void setGender(Integer gender) {
    33. this.gender = gender;
    34. }
    35. public Department getDepartment() {
    36. return department;
    37. }
    38. public void setDepartment(Department department) {
    39. this.department = department;
    40. }
    41. public Date getBirth() {
    42. return birth;
    43. }
    44. public void setBirth(Date birth) {
    45. this.birth = birth;
    46. }
    47. public Employee(Integer id, String lastName, String email, Integer gender,
    48. Department department) {
    49. super();
    50. this.id = id;
    51. this.lastName = lastName;
    52. this.email = email;
    53. this.gender = gender;
    54. this.department = department;
    55. this.birth = new Date();
    56. }
    57. public Employee() {
    58. }
    59. @Override
    60. public String toString() {
    61. return "Employee{" +
    62. "id=" + id +
    63. ", lastName='" + lastName + '\'' +
    64. ", email='" + email + '\'' +
    65. ", gender=" + gender +
    66. ", department=" + department +
    67. ", birth=" + birth +
    68. '}';
    69. }
    70. }

2、Restful 风格的 URL

实验功能 请求 URI 请求方式
查询所有员工 emps GET
查询某个员工 (来到修改页面) emp/1 GET
来到添加页面 emp GET
添加员工 emp POST
来到修改页面(查出员工进行信息回显) emp/1 GET
修改员工 emp PUT
删除员工 emp/1 DELETE

3、模板布局

考虑到员工的 CRUD 的页面会有许多公共的元素,所以将公共元素抽取出来作为模板。

  1. └─templates
  2. dashboard.html
  3. login.html

  4. ├─commons
  5. sidebar.html
  6. topbar.html

  7. ├─emps
  8. add.html
  9. list.html

注意下面的 html 页面都是最终修改后的页面(省略了繁琐的优化过程),页面里面的一些细节,后面会介绍一些。

1、dashboard.html(后台首页)

  1. <!DOCTYPE html>
  2. <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  7. <meta name="description" content="">
  8. <meta name="author" content="">
  9. <title>Dashboard Template for Bootstrap</title>
  10. <!-- Bootstrap core CSS -->
  11. <link href="/asserts/css/bootstrap.min.css" rel="stylesheet">
  12. <!-- Custom styles for this template -->
  13. <link href="/asserts/css/dashboard.css" rel="stylesheet">
  14. <style type="text/css">
  15. /* Chart.js */
  16. @-webkit-keyframes chartjs-render-animation {
  17. from {
  18. opacity: 0.99
  19. }
  20. to {
  21. opacity: 1
  22. }
  23. }
  24. @keyframes chartjs-render-animation {
  25. from {
  26. opacity: 0.99
  27. }
  28. to {
  29. opacity: 1
  30. }
  31. }
  32. .chartjs-render-monitor {
  33. -webkit-animation: chartjs-render-animation 0.001s;
  34. animation: chartjs-render-animation 0.001s;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <!--引入 top bar-->
  40. <div th:replace="commons/topbar::topbar">
  41. </div>
  42. <div class="container-fluid">
  43. <div class="row">
  44. <!--引入 side bar-->
  45. <div th:replace="commons/sidebar::sidebar(activeUrl='main.html')">
  46. </div>
  47. <!--Content-->
  48. <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  49. <div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;">
  50. <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
  51. <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
  52. </div>
  53. <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
  54. <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
  55. </div>
  56. </div>
  57. <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pb-2 mb-3 border-bottom">
  58. <h1 class="h2">Dashboard</h1>
  59. <div class="btn-toolbar mb-2 mb-md-0">
  60. <div class="btn-group mr-2">
  61. <button class="btn btn-sm btn-outline-secondary">Share</button>
  62. <button class="btn btn-sm btn-outline-secondary">Export</button>
  63. </div>
  64. <button class="btn btn-sm btn-outline-secondary dropdown-toggle">
  65. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-calendar"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>
  66. This week
  67. </button>
  68. </div>
  69. </div>
  70. <canvas class="my-4 chartjs-render-monitor" id="myChart" width="1076" height="454" style="display: block; width: 1076px; height: 454px;"></canvas>
  71. </main>
  72. </div>
  73. </div>
  74. <!-- Bootstrap core JavaScript
  75. ================================================== -->
  76. <!-- Placed at the end of the document so the pages load faster -->
  77. <script type="text/javascript" src="/asserts/js/jquery-3.2.1.slim.min.js" ></script>
  78. <script type="text/javascript" src="/asserts/js/popper.min.js" ></script>
  79. <script type="text/javascript" src="/asserts/js/bootstrap.min.js" ></script>
  80. <!-- Icons -->
  81. <script type="text/javascript" src="/asserts/js/feather.min.js" ></script>
  82. <script>
  83. feather.replace()
  84. </script>
  85. <!-- Graphs -->
  86. <script type="text/javascript" src="/asserts/js/Chart.min.js" ></script>
  87. <script>
  88. var ctx = document.getElementById("myChart");
  89. var myChart = new Chart(ctx, {
  90. type: 'line',
  91. data: {
  92. labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  93. datasets: [{
  94. data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
  95. lineTension: 0,
  96. backgroundColor: 'transparent',
  97. borderColor: '#007bff',
  98. borderWidth: 4,
  99. pointBackgroundColor: '#007bff'
  100. }]
  101. },
  102. options: {
  103. scales: {
  104. yAxes: [{
  105. ticks: {
  106. beginAtZero: false
  107. }
  108. }]
  109. },
  110. legend: {
  111. display: false,
  112. }
  113. }
  114. });
  115. </script>
  116. </body>
  117. </html>

2、sidebar.html(侧边栏模板)

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <!--side bar-->
  9. <nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
  10. <div class="sidebar-sticky">
  11. <ul class="nav flex-column">
  12. <li class="nav-item">
  13. <a class="nav-link active" href="#" th:href="@{/main.html}" th:class="${activeUrl}=='main.html'?'nav-link active':'nav-link'">
  14. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
  15. <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
  16. <polyline points="9 22 9 12 15 12 15 22"></polyline>
  17. </svg>
  18. Dashboard <span class="sr-only">(current)</span>
  19. </a>
  20. </li>
  21. <li class="nav-item">
  22. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  23. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
  24. <path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
  25. <polyline points="13 2 13 9 20 9"></polyline>
  26. </svg>
  27. Orders
  28. </a>
  29. </li>
  30. <li class="nav-item">
  31. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
  32. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
  33. <circle cx="9" cy="21" r="1"></circle>
  34. <circle cx="20" cy="21" r="1"></circle>
  35. <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
  36. </svg>
  37. Products
  38. </a>
  39. </li>
  40. <li class="nav-item">
  41. <a class="nav-link" href="#" th:href="@{/emps}" th:class="${activeUrl}=='emps'?'nav-link active':'nav-link'">
  42. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
  43. <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
  44. <circle cx="9" cy="7" r="4"></circle>
  45. <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
  46. <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
  47. </svg>
  48. 员工管理
  49. </a>
  50. </li>
  51. <li class="nav-item">
  52. <a class="nav-link" href="#">
  53. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2">
  54. <line x1="18" y1="20" x2="18" y2="10"></line>
  55. <line x1="12" y1="20" x2="12" y2="4"></line>
  56. <line x1="6" y1="20" x2="6" y2="14"></line>
  57. </svg>
  58. Reports
  59. </a>
  60. </li>
  61. <li class="nav-item">
  62. <a class="nav-link" href="#">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers">
  64. <polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
  65. <polyline points="2 17 12 22 22 17"></polyline>
  66. <polyline points="2 12 12 17 22 12"></polyline>
  67. </svg>
  68. Integrations
  69. </a>
  70. </li>
  71. </ul>
  72. <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
  73. <span>Saved reports</span>
  74. <a class="d-flex align-items-center text-muted" href="#">
  75. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
  76. </a>
  77. </h6>
  78. <ul class="nav flex-column mb-2">
  79. <li class="nav-item">
  80. <a class="nav-link" href="#">
  81. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  82. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  83. <polyline points="14 2 14 8 20 8"></polyline>
  84. <line x1="16" y1="13" x2="8" y2="13"></line>
  85. <line x1="16" y1="17" x2="8" y2="17"></line>
  86. <polyline points="10 9 9 9 8 9"></polyline>
  87. </svg>
  88. Current month
  89. </a>
  90. </li>
  91. <li class="nav-item">
  92. <a class="nav-link" href="#">
  93. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  94. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  95. <polyline points="14 2 14 8 20 8"></polyline>
  96. <line x1="16" y1="13" x2="8" y2="13"></line>
  97. <line x1="16" y1="17" x2="8" y2="17"></line>
  98. <polyline points="10 9 9 9 8 9"></polyline>
  99. </svg>
  100. Last quarter
  101. </a>
  102. </li>
  103. <li class="nav-item">
  104. <a class="nav-link" href="#">
  105. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  106. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  107. <polyline points="14 2 14 8 20 8"></polyline>
  108. <line x1="16" y1="13" x2="8" y2="13"></line>
  109. <line x1="16" y1="17" x2="8" y2="17"></line>
  110. <polyline points="10 9 9 9 8 9"></polyline>
  111. </svg>
  112. Social engagement
  113. </a>
  114. </li>
  115. <li class="nav-item">
  116. <a class="nav-link" href="#">
  117. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
  118. <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
  119. <polyline points="14 2 14 8 20 8"></polyline>
  120. <line x1="16" y1="13" x2="8" y2="13"></line>
  121. <line x1="16" y1="17" x2="8" y2="17"></line>
  122. <polyline points="10 9 9 9 8 9"></polyline>
  123. </svg>
  124. Year-end sale
  125. </a>
  126. </li>
  127. </ul>
  128. </div>
  129. </nav>
  130. </body>
  131. </html>

3、topbar.html(顶部栏模板)

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <!--top bar-->
  9. <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment = "topbar">
  10. <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">[[${session.user}]]</a>
  11. <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
  12. <ul class="navbar-nav px-3">
  13. <li class="nav-item text-nowrap">
  14. <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
  15. </li>
  16. </ul>
  17. </nav>
  18. </body>
  19. </html>

4、list.html(员工列表页面)

  1. <!DOCTYPE html>
  2. <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  7. <meta name="description" content="">
  8. <meta name="author" content="">
  9. <title>Dashboard Template for Bootstrap</title>
  10. <!-- Bootstrap core CSS -->
  11. <link href="/asserts/css/bootstrap.min.css" rel="stylesheet">
  12. <!-- Custom styles for this template -->
  13. <link href="/asserts/css/dashboard.css" rel="stylesheet">
  14. <style type="text/css">
  15. /* Chart.js */
  16. @-webkit-keyframes chartjs-render-animation {
  17. from {
  18. opacity: 0.99
  19. }
  20. to {
  21. opacity: 1
  22. }
  23. }
  24. @keyframes chartjs-render-animation {
  25. from {
  26. opacity: 0.99
  27. }
  28. to {
  29. opacity: 1
  30. }
  31. }
  32. .chartjs-render-monitor {
  33. -webkit-animation: chartjs-render-animation 0.001s;
  34. animation: chartjs-render-animation 0.001s;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <!--引入 top bar-->
  40. <div th:replace="commons/topbar::topbar">
  41. </div>
  42. <div class="container-fluid">
  43. <div class="row">
  44. <!--引入 side bar-->
  45. <div th:replace="commons/sidebar::sidebar(activeUrl='emps')">
  46. </div>
  47. <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  48. <h2><a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}"> 员工添加 </a></h2>
  49. <div class="table-responsive">
  50. <table class="table table-striped table-sm">
  51. <thead>
  52. <tr>
  53. <th>#</th>
  54. <th>lastName</th>
  55. <th>email</th>
  56. <th>gender</th>
  57. <th>department</th>
  58. <th>birth</th>
  59. <th> 操作 </th>
  60. </tr>
  61. </thead>
  62. <tbody>
  63. <tr th:each="emp:${emps}">
  64. <td th:text="${emp.id}"></td>
  65. <td th:text="${emp.lastName}"></td>
  66. <td th:text="${emp.email}"></td>
  67. <td th:text="${emp.gender}=='0'?' 女 ':' 男 '"></td>
  68. <td th:text="${emp.department.departmentName}"></td>
  69. <td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td>
  70. <td>
  71. <a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}"> 编辑 </a>
  72. <!-- Button trigger modal -->
  73. <button type="button" class="btn btn-danger btn-sm" data-toggle="modal" th:attr="data-target=@{#del}+${emp.id}">
  74. 删除
  75. </button>
  76. <!-- Modal -->
  77. <div class="modal fade" th:id="@{del}+${emp.id}" tabindex="-1" role="dialog"th:attr="aria-labelledby=@{delLabe}+${emp.id}" aria-hidden="true">
  78. <div class="modal-dialog" role="document">
  79. <div class="modal-content">
  80. <div class="modal-header">
  81. <h5 class="modal-title" th:id="@{delLabe}+${emp.id}"> 删除员工 </h5>
  82. <button type="button" class="close" data-dismiss="modal" aria-label="Close">
  83. <span aria-hidden="true">&times;</span>
  84. </button>
  85. </div>
  86. <div class="modal-body">
  87. <p class="text-danger"> 确定要删除?该操作不可撤销!</p>
  88. </div>
  89. <div class="modal-footer">
  90. <button type="button" class="btn btn-secondary" data-dismiss="modal"> 取消 </button>
  91. <button type="button" class="btn btn-primary deleteBtn" th:attr="delurl=@{/emp/}+${emp.id}"> 确定 </button>
  92. </div>
  93. </div>
  94. </div>
  95. </div>
  96. </td>
  97. </tr>
  98. </tbody>
  99. </table>
  100. </div>
  101. </main>
  102. <form id="delForm" method="post">
  103. <input type="hidden" name="_method" value="delete">
  104. </form>
  105. </div>
  106. </div>
  107. <!-- Bootstrap core JavaScript
  108. ================================================== -->
  109. <!-- Placed at the end of the document so the pages load faster -->
  110. <script type="text/javascript" src="/asserts/js/jquery-3.2.1.slim.min.js"></script>
  111. <script type="text/javascript" src="/asserts/js/popper.min.js"></script>
  112. <script type="text/javascript" src="/asserts/js/bootstrap.min.js"></script>
  113. <!-- Icons -->
  114. <script type="text/javascript" src="/asserts/js/feather.min.js"></script>
  115. <script>
  116. feather.replace();
  117. </script>
  118. <script>
  119. $(document).ready(function () {
  120. $(".deleteBtn").click(function () {
  121. $("#delForm").attr("action",$(this).attr("delurl")).submit();
  122. });
  123. });
  124. </script>
  125. </body>
  126. </html>

5、add.html(员工的添加、修改二合一页面)

  1. <!DOCTYPE html>
  2. <!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  7. <meta name="description" content="">
  8. <meta name="author" content="">
  9. <title>Dashboard Template for Bootstrap</title>
  10. <!-- Bootstrap core CSS -->
  11. <link href="/asserts/css/bootstrap.min.css" rel="stylesheet">
  12. <!-- Custom styles for this template -->
  13. <link href="/asserts/css/dashboard.css" rel="stylesheet">
  14. <style type="text/css">
  15. /* Chart.js */
  16. @-webkit-keyframes chartjs-render-animation {
  17. from {
  18. opacity: 0.99
  19. }
  20. to {
  21. opacity: 1
  22. }
  23. }
  24. @keyframes chartjs-render-animation {
  25. from {
  26. opacity: 0.99
  27. }
  28. to {
  29. opacity: 1
  30. }
  31. }
  32. .chartjs-render-monitor {
  33. -webkit-animation: chartjs-render-animation 0.001s;
  34. animation: chartjs-render-animation 0.001s;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <!--引入 top bar-->
  40. <div th:replace="commons/topbar::topbar">
  41. </div>
  42. <div class="container-fluid">
  43. <div class="row">
  44. <!--引入 side bar-->
  45. <div th:replace="commons/sidebar::sidebar(activeUrl='emps')">
  46. </div>
  47. <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  48. <!--需要区分是员工修改还是添加;-->
  49. <form th:action="@{/emp}" method="post">
  50. <!--添加隐藏域,用于发送 put 请求修改表单-->
  51. <input type="hidden" name="_method" value="put" th:if="${emp!=null}"/>
  52. <input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}">
  53. <div class="form-group">
  54. <label>LastName</label>
  55. <input name="lastName" type="text" class="form-control" placeholder="zhangsan" th:value="${emp}!=null?${emp.lastName}:''">
  56. </div>
  57. <div class="form-group">
  58. <label>Email</label>
  59. <input name="email" type="text" class="form-control" placeholder="xxx@qq.com"
  60. th:value="${emp}!=null?${emp.email}:''">
  61. </div>
  62. <div class="form-group">
  63. <label>Gender</label>
  64. <div class="form-check form-check-inline">
  65. <input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp}!=null?(${emp.gender}==1):false">
  66. <label class="form-check-label"></label>
  67. </div>
  68. <div class="form-check form-check-inline">
  69. <input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp}!=null?(${emp.gender}==0):false">
  70. <label class="form-check-label"></label>
  71. </div>
  72. </div>
  73. <div class="form-group">
  74. <label>Department</label>
  75. <select class="form-control" name="department.id">
  76. <option th:selected="${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${departments}" th:text="${dept.departmentName}" th:if="${emp!=null}"></option>
  77. <option th:value="${dept.id}" th:each="dept:${departments}" th:text="${dept.departmentName}" th:if="${emp==null}"></option>
  78. </select>
  79. </div>
  80. <div class="form-group">
  81. <label>Birth</label>
  82. <input name="birth" type="text" class="form-control" placeholder="2017/01/01 12:23" th:value="${emp!=null}?${#dates.format(emp.birth,'yyyy/MM/dd HH:mm')}">
  83. </div>
  84. <button type="submit" class="btn btn-primary" th:text="${emp==null}?' 添加 ':' 修改 '"> 添加 </button>
  85. </form>
  86. </main>
  87. </div>
  88. </div>
  89. <!-- Bootstrap core JavaScript
  90. ================================================== -->
  91. <!-- Placed at the end of the document so the pages load faster -->
  92. <script type="text/javascript" src="/asserts/js/jquery-3.2.1.slim.min.js" ></script>
  93. <script type="text/javascript" src="/asserts/js/popper.min.js" ></script>
  94. <script type="text/javascript" src="/asserts/js/bootstrap.min.js" ></script>
  95. <!-- Icons -->
  96. <script type="text/javascript" src="/asserts/js/feather.min.js" ></script>
  97. <script>
  98. feather.replace()
  99. </script>
  100. </body>
  101. </html>

4、EmployeeController(处理员工请求控制器)

  1. package com.yunche.controller;
  2. import com.yunche.dao.DepartmentDao;
  3. import com.yunche.dao.EmployeeDao;
  4. import com.yunche.entities.Employee;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.*;
  9. /**
  10. * @ClassName: EmployeeController
  11. * @Description:
  12. * @author: yunche
  13. * @date: 2019/01/03
  14. */
  15. @Controller
  16. public class EmployeeController {
  17. @Autowired
  18. EmployeeDao employeeDao;
  19. @Autowired
  20. DepartmentDao departmentDao;
  21. @GetMapping("/emps")
  22. public String list(Model model) {
  23. model.addAttribute("emps", employeeDao.getAll());
  24. return "emps/list";
  25. }
  26. /**
  27. * 来到添加页面
  28. *
  29. * @return
  30. */
  31. @GetMapping("/emp")
  32. public String toAddPage(Model model) {
  33. model.addAttribute("departments", departmentDao.getDepartments());
  34. return "emps/add";
  35. }
  36. /**
  37. * 添加员工
  38. * SpringMVC 自动将请求参数和入参对象的属性进行一一绑定;
  39. * 要求请求参数的名字和 javaBean 入参的对象里面的属性名是一样的
  40. * @return
  41. */
  42. @PostMapping("/emp")
  43. public String addEmployee(Employee employee) {
  44. employeeDao.save(employee);
  45. return "redirect:/emps";
  46. }
  47. /**
  48. * 来到修改页面
  49. *
  50. * @return
  51. */
  52. @GetMapping("/emp/{id}")
  53. public String toEditPage(@PathVariable("id") Integer id, Model model) {
  54. Employee employee = employeeDao.get(id);
  55. model.addAttribute("emp", employee);
  56. model.addAttribute("departments", departmentDao.getDepartments());
  57. return "emps/add";
  58. }
  59. /**
  60. * 修改员工
  61. * @param employee
  62. * @return
  63. */
  64. @PutMapping("/emp")
  65. public String editEmployee(Employee employee) {
  66. employeeDao.save(employee);
  67. return "redirect:/emps";
  68. }
  69. /**
  70. * 删除员工
  71. * @param id
  72. * @return
  73. */
  74. @DeleteMapping("/emp/{id}")
  75. public String removeEmployee(@PathVariable("id") Integer id) {
  76. employeeDao.delete(id);
  77. return "redirect:/emps";
  78. }
  79. }

5、细节讲解

1、PUT、DELTE 请求

由于 form 表单只允许使用 POST 请求,那么怎么以 PUT、DELETE 请求提交表单呢?可以在表单中添加一个隐藏域(Spring Boot 中 的 WebMvcAutoConfiguration 中有相应处理隐藏域的方法),使用隐藏域来达到以 PUT、DELETE 请求提交表单的效果。如:

  1. <!--添加隐藏域,用于发送 put 请求修改表单-->
  2. <input type="hidden" name="_method" value="put" th:if="${emp!=null}"/>

2、给模板页面传参

在这里的例子是我们要实现当进入后台首页时,侧边栏上的 dashboard 高亮;当进入员工管理时,侧边栏的员工管理高亮。要实现这样的效果,我们可以使用给模板页面传参的方式,用来区别到底进入了哪个页面,然后根据参数的不同,来实现相应的效果。

比如给模板页面传入参数:

  1. <!--引入 side bar-->
  2. <div th:replace="commons/sidebar::sidebar(activeUrl='emps')">
  3. </div>

根据参数的值实现相应的效果:

  1. <li class="nav-item">
  2. <a class="nav-link" href="#" th:href="@{/emps}" th:class="${activeUrl}=='emps'?'nav-link active':'nav-link'">
  3. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
  4. <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
  5. <circle cx="9" cy="7" r="4"></circle>
  6. <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
  7. <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
  8. </svg>
  9. 员工管理
  10. </a>
  11. </li>

3、添加、修改页面共用

我们添加、修改是共用一个页面的,所以应该根据某个变量来区分,到底该显示添加页面的效果还是修改页面的效果。在这里是通过 emp 变量, 如果页面能够获取到 emp 变量的值,说明应该进行修改操作;否则,进行添加操作。

  1. model.addAttribute("emp", employee);
  1. <button type="submit" class="btn btn-primary" th:text="${emp==null}?' 添加 ':' 修改 '"> 添加 </button>

6、定制错误页面

重新修改拦截器,便于演示。

MyMvcConfig:

  1. @Override
  2. public void addInterceptors(InterceptorRegistry registry) {
  3. // //排除静态资源的拦截:*.css , *.js
  4. // registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html", "/index", "/user/login", "/asserts/**","/webjars/**");
  5. registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/main.html", "/emps", "/emp/*");
  6. }

默认的处理方法是根据相应状态码的值,在 templates/error 中的文件夹中寻找相应匹配的 html 页面,可以

编写 4xx.html, 5xx.html,也可编写 404.html,精确优先。

404.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>404 NOT FOUND</title>
  6. </head>
  7. <body>
  8. <img src="/asserts/img/very_sorry.png">
  9. </body>
  10. </html>

7、阶段演示效果

一个小demo熟悉Spring Boot 和 thymeleaf 的基本使用的更多相关文章

  1. Spring Boot 2 + Thymeleaf:表单字段绑定、表单提交处理

    Spring Boot中Thymeleaf对表单处理的一些用法:(1)使用th:field属性:进行表单字段绑定(2)使用ids对象:一般用于lable配合radio或checkbox使用(3)表单提 ...

  2. java线程间通信:一个小Demo完全搞懂

    版权声明:本文出自汪磊的博客,转载请务必注明出处. Java线程系列文章只是自己知识的总结梳理,都是最基础的玩意,已经掌握熟练的可以绕过. 一.从一个小Demo说起 上篇我们聊到了Java多线程的同步 ...

  3. spring boot 与 thymeleaf (2): 常用表达式

    在asp.net mvc 中, 有一个视图解析器, 可以支持Razor语法. 使用起来, 是非常的方便, 并且, 写在前台页面的后台方法, 是可调试的. 但是在java中, 目前我还没有接触到, 像. ...

  4. 小代学Spring Boot之数据源

    想要获取更多文章可以访问我的博客 - 代码无止境. 经过一天对Spring Boot的研究,小代同学已经对Spring Boot框架有了一个大概的认识.并且还创建了一个简单的Spring Boot的W ...

  5. 小代学Spring Boot之集成MyBatis

    想要获取更多文章可以访问我的博客 - 代码无止境. 上一篇小代同学在Spring Boot项目中配置了数据源,但是通常来讲我们访问数据库都会通过一个ORM框架,很少会直接使用JDBC来执行数据库操作的 ...

  6. 小代学Spring Boot之自定义Starter

    想要获取更多文章可以访问我的博客 - 代码无止境. 上一篇小代同学在Spring Boot项目中配置了数据源,但是通常来讲我们访问数据库都会通过一个ORM框架,很少会直接使用JDBC来执行数据库操作的 ...

  7. Spring Boot2 系列教程(九)Spring Boot 整合 Thymeleaf

    虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板, ...

  8. Spring Boot 2 + Thymeleaf:服务器端表单验证

    表单验证分为前端验证和服务器端验证.服务器端验证方面,Java提供了主要用于数据验证的JSR 303规范,而Hibernate Validator实现了JSR 303规范.项目依赖加入spring-b ...

  9. 极简 Spring Boot 整合 Thymeleaf 页面模板

    虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板, ...

随机推荐

  1. YTU 2677: 韩信点兵

    2677: 韩信点兵 时间限制: 1 Sec  内存限制: 128 MB 提交: 61  解决: 38 题目描述 刘邦问韩信:"你觉得我可以带兵多少?"韩信:"最多十万. ...

  2. [noip模拟赛]跑跑步

    https://www.zybuluo.com/ysner/note/1298652 题面 小胡同学是个热爱运动的好孩子. 每天晚上,小胡都会去操场上跑步,学校的操场可以看成一个由\(n\)个格子排成 ...

  3. Face alignment at 3000FPS via Regressing Local Binrary features 理解

    这篇是Ren Shaoqing发表在cvpr2014上的paper,论文是在CPR框架下做的,想了解CPR的同学可以参见我之前的博客,网上有同学给出了code,该code部分实现了LBF,链接为htt ...

  4. java笔记线程方式1优先级

    * 我们的线程没有设置优先级,肯定有默认优先级. * 那么,默认优先级是多少呢? * 如何获取线程对象的优先级? *   public final int getPriority():返回线程对象的优 ...

  5. 给网站添加免费Https SSL证书

    基于阿里云的云盾证书服务,系统是centos6.8,web服务器是nginx1.8.0,简单记录下踩坑情况. 申请证书 登录阿里云控制台→安全(云盾)→证书服务→购买证书(https://common ...

  6. Builder Design pattern

    string assemblyName = ConfigurationSettings["BuilderAssembly"]; string builderName = Confi ...

  7. bzoj 1644: [Usaco2007 Oct]Obstacle Course 障碍训练课【spfa】

    洛谷的数据毒啊 把(i,j,k)作为一个点spfa,表示点(i,j)朝向k方向,然后向四个方向转移即可 #include<iostream> #include<cstdio> ...

  8. bzoj 1741: [Usaco2005 nov]Asteroids 穿越小行星群【最大点覆盖】

    二分图最大点覆盖模型,因为对于一个点(x,y)显然只要选x或者y就好了,于是连边,跑最大匹配=最大点覆盖(不会证) #include<iostream> #include<cstdi ...

  9. GG_Model 类库与数据库表对应建立实体类

    3.4.GG_Model 类库与数据库表对应建立实体类 我这里不教大家写代码,直接用TT模板自动生成,省去写代码的麻烦. A. 三个文件MysqlDbhelper.ttinclude .mysqlMa ...

  10. javascript实现继承的4种方法,以及它们的优缺点

    1. 原型链继承(有缺陷): 缺陷1:切断了Zi.prototype.constructor与Zi的关系 缺陷2:原型链上的引用类型的数据会被所有实例共享 2. 构造函数继承(有缺陷): 缺陷1:Fu ...