SpringBoot-06 员工管理系统
一、环境搭建
1.新建SpringBoot项目
具体步骤如图:
![1](https://i-blog.csdnimg.cn/blog_migrate/dc006ccf82e550abefad1ae2eb7c182d.png)
![2](https://i-blog.csdnimg.cn/blog_migrate/19a3d16f940c94ca5557803678a84d4d.png)
![3](https://i-blog.csdnimg.cn/blog_migrate/788b4087b40986797003a5cf9e0a9891.png)
之后就是起好项目名,然后完成创建。
![4](https://i-blog.csdnimg.cn/blog_migrate/85b5903bb7270577c77befe918823bc8.png)
红框中的可以自行选择删除,不删除也没事情。
2.导入静态资源
**静态资源文件:**https://pan.baidu.com/s/1xjkUFp0ke73tUxM6SUJaSw
**提取码:**m2yf
或者大家自己自己下载一个静态资源文件:
**BootStrap静态模板:**https://getbootstrap.com/docs/4.0/examples/
- 将
html
文件放入templates
文件夹 asserts
中的css、js、img
文件夹放入static
文件夹(或者public、resources,看心情)
![6](https://i-blog.csdnimg.cn/blog_migrate/e74ee771e02e3470491b25c9890147df.png)
3.模拟数据库
创建pojo、dao、Controller包,记得要在启动器同级目录下创建。
- pojo实体类 作为 数据库表
- dao实现类 作为 添加原始数据以及数据库操作。
3.1 pojo实体类
部门类,Department:
//部门表
public class Department {
private Integer id; //部门id
private String departmentName; //部门名称
// 有参/无参方法
// Get/Set方法
// toString()方法
}
员工类,Employee:
//员工表
public class Employee {
private Integer id; //员工id
private String lastName; //员工姓名
private String email; //员工邮箱
private Integer gender; //员工性别 0 女 1 男
private Department department; //员工部门
private Date birth; //员工生日
// 有参/无参方法
// Get/Set方法
// toString()方法
}
这里需要注意这个员工生日,你可以在实体类中让他自己创建:
// 参数中删除 Date date
public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
this.birth = new Date(); //默认创建日期
}
当然,你也可以在之后添加数据的时候,每次在date
对应位置写 new Date()
;
3.2 dao实现类
部门dao类,DepartmentDao:
@Repository //注册进Spring容器
public class DepartmentDao {
//模拟数据库中数据
private static Map<Integer, Department> departments = null;
static {
departments = new HashMap<>(); //创建部门表
departments.put(101,new Department(101,"教学部"));
departments.put(102,new Department(102,"市场部"));
departments.put(103,new Department(103,"教研部"));
departments.put(104,new Department(104,"运营部"));
departments.put(105,new Department(105,"后勤部"));
}
//数据库操作
//获取所有部门信息
public Collection<Department> getDepartments(){
return departments.values();
}
//通过id获得部门
public Department getDepartment(Integer id){
return departments.get(id);
}
}
员工dao类,EmployeeDao:
@Repository
public class EmployeeDao {
//模拟数据库
private static Map<Integer, Employee> employees = null;
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap<Integer, Employee>();
employees.put(1001,new Employee(1001,"AA","1@qq.com",1,new Department(101,"教学部")));
employees.put(1002,new Employee(1002,"BB","2@qq.com",0,new Department(102,"市场部")));
employees.put(1003,new Employee(1003,"CC","3@qq.com",1,new Department(103,"教研部")));
employees.put(1004,new Employee(1004,"DD","4@qq.com",1,new Department(104,"运营部")));
employees.put(1005,new Employee(1005,"EE","5@qq.com",0,new Department(105,"后勤部")));
}
//主键自增
private static Integer id=1006;
//数据操作
//增加一个员工
public void save(Employee employee){
if (employee.getId()==null){
employee.setId(id++);
} employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
employees.put(employee.getId(),employee);
}
//查询全部员工信息
public Collection<Employee> getEmployees(){
return employees.values();
}
//通过id查询员工
public Employee getEmployee(Integer id){
return employees.get(id);
}
//删除员工
public void delEmployee(Integer id){
employees.remove(id);
}
}
以上,环境搭建完成。
二、首页以及前端路径改写
1.首先得先让http://localhost:8080/这个路径可以直接访问index.html
![7](https://i-blog.csdnimg.cn/blog_migrate/51149e0dfb4cd2a8af2156f56ae475af.png)
这时候可以看到,网页是正常访问的,但是静态资源都没有加载。
2.加载静态资源
<html lang="en" xmlns:th="http://www.thymeleaf.org">
-
在html文件头部加入thymeleaf头文件
-
将html页面静态资源的标签改为th:xxx
-
加载路径规则:@{xxx}
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/css/signin.css}" rel="stylesheet">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
之后最后一步:关闭模板引擎缓存
spring.thymeleaf.cache=false
![8](https://i-blog.csdnimg.cn/blog_migrate/f8139db244cdae5bf414a8fdad977daa.png)
然后把全部的前端页面都改写就可以了。
三、页面国际化
首先,要确定你的项目是UTF-8:
![9](https://i-blog.csdnimg.cn/blog_migrate/79befe9cb3e29b9b3826b939a070d2c9.png)
3.1 实现跟随浏览器语言切换
1.在resources中创建一个i18n文件夹,中间创建login.properties(默认语言)、login_zh_CN.properties(汉语)、**login_en_US.properties(英语) ** 【直接创建,会自动合并】
2.配置语言,你可以选择一个文件一个文件输入,也可以进行可视化输入
![11](https://i-blog.csdnimg.cn/blog_migrate/39b10d142a9b81b7cc45d96a2bfaf9bb.png)
login.password=密码
login.tip=请登录
login.remember=记住我
login.btn=登录
login.username=用户名
login.password=password
login.tip=Please sign in
login.remember=Remember me
login.btn=Sign in
login.username=username
3.开启国际化 i18n下的login
spring.messages.basename=i18n.login
4.修改html文件,以index.html为例
对于国际化信息用 #{ xxxx }
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" th:text="#{login.remember}">
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" >[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
![12](https://i-blog.csdnimg.cn/blog_migrate/e240cdeb5841e1cd3ef9caac09e72043.png)
3.2 实现跟随按钮切换
1.先给两个按钮使用跳转地址
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
2.自定义国际化组件
可以在config文件夹下创建一个MyLocalResolver类
public class MyLocalResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
//获取请求中的参数
String language = httpServletRequest.getParameter("l");
//如果没有就默认
Locale locale = Locale.getDefault();
//如果请求连接携带了国际化参数
if (!StringUtils.isEmpty(language)){
String[] l = language.split("_");
//国家、地区
locale=new Locale(l[0], l[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
3.在MyMvcConfig注册成Bean,使之生效
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
这样运行软件之后就可以进行点击按钮中英切换。
四、登陆页面实现
1.修改index.html
<body class="text-center">
<!--修改运行路径为 th:action="@{/login}" /login为Controller类设置路径 -->
<form class="form-signin" th:action="@{/login}">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--添加的一个错误语句,出现登陆错误可以显示 -->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only" th:text="#{login.username}">Username</label>
<!--添加name="username",值可以传递到后端 -->
<input type="text" class="form-control" th:placeholder="#{login.username}" name="username" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<!--添加name="password",值可以传递到后端 -->
<input type="password" class="form-control" th:placeholder="#{login.password}" name="password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" th:text="#{login.remember}">
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" >[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
2.编写控制类
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
// 具体业务 当username不为空并且密码为123456时可以登录,不然返回错误信息msg
if (!StringUtils.isEmpty(username)&&password.equals("123456")){
return "dashboard";
}else {
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
}
3.测试运行
输入错误时:
![13](https://i-blog.csdnimg.cn/blog_migrate/72dbb743897ab74df3d3c207f742ff67.png)
成功登录时:
![14](https://i-blog.csdnimg.cn/blog_migrate/f2ec4102fb4a26ccc473b27434c14fad.png)
4.路径优化
看上图登录成功页面路径,可以看出,登录参数一览无余;
这样肯定是不安全的,所以我们要进行路径优化
思路:当我们访问 http://localhost:8080/main.html 可以进入主页面
第一步:在MyMvcConfig添加一个main.html的映射
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
//添加一个main.html的映射
registry.addViewController("/main.html").setViewName("dashboard.html");
}
第二步:使登陆成功时,重定向到main.html,修改Controller
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
// 具体业务
if (!StringUtils.isEmpty(username)&&password.equals("123456")){
//重定向到main.html
return "redirect:/main.html";
}else {
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
![15](https://i-blog.csdnimg.cn/blog_migrate/c6d5cda23eebf1197b8aadb3ee1be61a.png)
登陆成功页面成功变换
五、登录拦截器
1.更改Controller类,登录后将username存入session域中
@RequestMapping("/login")
// @ResponseBody
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session){
// 具体业务
if (!StringUtils.isEmpty(username)&&password.equals("123456")){
// 存入session
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else {
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
}
2.在config创建拦截器类
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功之后,应该有用户Session
Object loginUser = request.getSession().getAttribute("loginUser");
if (loginUser==null){
//没有登陆
request.setAttribute("msg","你没有权限,请登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}
else {
return true;
}
}
}
3.在MyMvcConfig添加一个拦截器的映射
@Override
public void addInterceptors(InterceptorRegistry registry) {
// /** 拦截全部资源;不包括 /,/login,/index.html,/css/*,/img/*,/js/* 路径下的资源。
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/login","/index.html","/css/*","/img/*","/js/*");
}
六、展示员工列表
6.1 引入员工页面
直接导入的网页里面的跳转链接都是默认自带的,我们需要修改为自己的页面。
一、编写Controller
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@RequestMapping("/emps")
public String getAllemployee(Model model){
Collection<Employee> employees = employeeDao.getEmployees();
model.addAttribute("emp",employees);
//新创建了一个emp文件夹,将list.html放里面
return "emp/list";
}
}
二、修改侧边栏员工部分的跳转链接
<li class="nav-item">
<!-- th:href="@{/emp}" 运行Controller类方法,跳转list.html -->
<a th:class="${active=='list.html'?'nav-link active':'nav-link' }" th:href="@{/emps}" >
<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">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
Customers
</a>
</li>
6.2 准备提取页面
我们可以看出,每个页面的 头部 和 侧边栏 都是重复的,所以我们可以把重复的部分提取出来,直接引入html文件中。
- 提取文件:th:fragment="xxxxx"
- 引入文件:th:replace="{xxxx}"**、**th:insert="{xxxx}"
第一步、在templates中创建一个commons文件夹,其中创建commons.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 顶部 th:fragment="topbar" -->
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
</li>
</ul>
</nav >
<!-- 侧边栏 th:fragment="sidebar" -->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
<a th:class="${active=='main.html'?'nav-link active':'nav-link' }" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<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">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
Dashboard <span class="sr-only">(current)</span>
</a>
</li>
..........中间省略
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<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">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Year-end sale
</a>
</li>
</ul>
</div>
</nav>
</html>
第二步、在其他html页面中把原来的头部、侧边代码删除,并在相同的位置引入
<!-- 顶部-->
<div th:replace="~{commons/commons::topbar}"></div>
<!-- 侧边栏-->
<div th:replace="~{commons/commons::sidebar}" ></div>
第三步、这里是为了在网页中,点击侧边的哪一个模块、哪一个模块对应的文字亮起来
思路:
- 跳转时传递一个参数
- 每个模块的参数用对应的html名字表示
- 在侧边栏代码中进行判断,对应的名字亮对应的部分
1.添加参数
例如,dashboard.html和list.html页面:
<div th:replace="~{commons/commons::sidebar(active='main.html')}" ></div>
<div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>
2.判断
使用 th:class="${active==‘xxx’?‘nav-link active’:‘nav-link’ }" 进行判断
<li class="nav-item">
<a th:class="${active=='main.html'?'nav-link active':'nav-link' }" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<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">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
Dashboard <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a th:class="${active=='list.html'?'nav-link active':'nav-link' }" th:href="@{/emps}" >
<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">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
Customers
</a>
</li>
6.3 展示员工列表
到了这一步,准备工作基本都完成了,开始在list.html展示
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>Section title</h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</th>
</tr>
</thead>
<tbody th:each="emp:${emps}">
<tr>
<td th:text="${emp.getId()}"></td>
<td th:text="${emp.getLastName()}"></td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender()==0?'女':'男 '}"></td>
<td th:text="${emp.getDepartment().getDepartmentName()}"></td>
<td th:text="${#dates.format(emp.getBirth(),'yyyy-mm-dd hh:mm:ss')}"></td>
<td>
<button class="btn btn-sm btn-primary">编辑</button>
<button class="btn btn-sm btn-danger">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
![16](https://i-blog.csdnimg.cn/blog_migrate/f9eb2fb0c9f2aa0ed476a259560940ad.png)
七、新增员工信息
1.首先写一个跳转到增加页面的方法
@GetMapping("/emp")
public String toAdd(Model model){
//查出所有部门信息
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
return "emp/add";
}
2.再新增一个add页面,在emp文件夹中:
from表单method要使用post
<!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="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/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::topbar}"></div>
<div class="container-fluid">
<div class="row">
<div th:replace="~{commons/commons::sidebar(active='list.html')}"></div>
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<form class="form-horizontal" th:action="@{/emp}" method="post">
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="lastName">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">邮箱</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="email" id="Email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">性别</label>
<div class="col-sm-10">
<input type="radio" class="form-check-input" name="gender" value="0">
<label class="col-sm-2 control-label">女</label>
<input type="radio" class="form-check-input" name="gender" value="1">
<label class="col-sm-2 control-label">男</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">部门</label>
<div class="col-sm-10">
<select class="form-control" name="department.id">
<option th:each="dept:${depts}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}">教学部</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">日期</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="birth" id="birth" placeholder="birth">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">提交</button>
</div>
</div>
</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>
3.编写增加员工Controller类方法
此时使用的路径仍是emp,但是因为是post传递,符合Restful风格。
@PostMapping("/emp")
public String Addemp(Employee employee){
System.out.println(employee);
//保存员工信息
employeeDao.save(employee);
return "redirect:/emps";
}
![17](https://i-blog.csdnimg.cn/blog_migrate/282306cfffd0fc0a3a02126926f50ac1.png)
八、修改员工信息
1.首先写一个跳转到修改页面的方法
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id") Integer id, Model model){
//查出对应数据
Employee employee = employeeDao.getEmployee(id);
model.addAttribute("emp",employee);
//查出所有部门信息
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
return "emp/update";
}
2.修改list页面中,编辑按钮的跳转路径
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.getId()}">编辑</a>
注意:这里的 ‘+’ 会报红,不用管
3.再新增一个update页面,在emp文件夹中:
from表单method要使用post
update页面可以直接复制add页面
以下为****内容
<form class="form-horizontal" th:action="@{/updateEmp}" method="post">
<input type="hidden" name="id" th:value="${emp.getId()}">
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input th:value="${emp.getLastName()}" type="text" class="form-control" name="lastName" id="lastName" placeholder="lastName">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">邮箱</label>
<div class="col-sm-10">
<input th:value="${emp.getEmail()}" type="email" class="form-control" name="email" id="Email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">性别</label>
<div class="col-sm-10">
<input th:checked="${emp.getGender()==0}" type="radio" class="form-check-input" name="gender" value="0">
<label class="col-sm-2 control-label">女</label>
<input th:checked="${emp.getGender()==1}" type="radio" class="form-check-input" name="gender" value="1">
<label class="col-sm-2 control-label">男</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">部门</label>
<div class="col-sm-10">
<select class="form-control" name="department.id">
<option th:selected="${dept.getId()==emp.getDepartment().getId()}" th:each="dept:${depts}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">日期</label>
<div class="col-sm-10">
<input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd hh:mm:ss')}" type="text" class="form-control" name="birth" id="birth" placeholder="birth">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">提交</button>
</div>
</div>
</form>
4.编写修改员工Controller类方法
@PostMapping("/updateEmp")
public String UpdateEmp(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
![18](https://i-blog.csdnimg.cn/blog_migrate/9707de58d57d00b8c28e4386b4c314e0.png)
九、删除员工信息
1.修改list页面-删除路径
<a class="btn btn-sm btn-danger" th:href="@{/delemp/}+${emp.getId()}">删除</a>
2.修改Controller类
@GetMapping("/delemp/{id}")
public String DelEmp(@PathVariable("id") Integer id){
employeeDao.delEmployee(id);
return "redirect:/emps";
}
十、404页面、注销操作
10.1 404页面
404页面是SpringBoot中最简单的功能:
- 在templates创建error文件夹
- 将404页面移入其中
- 搞定!
![19](https://i-blog.csdnimg.cn/blog_migrate/e46fb7ba8cacc638fcc2727224f3e8bd.png)
10.2 注销操作
1.编写Controller方法
@RequestMapping("/loginout")
public String loginout(HttpSession session){
//session.invalidate();
session.removeAttribute("loginUser");
return "redirect:index.html";
}
2.修改注销处跳转路径
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<!--跳转路径修改-->
<a class="nav-link" th:href="@{/loginout}">Sign out</a>
</li>
</ul>
</nav >
这样一个CRUD项目基本完成!
个人博客为:
MoYu’s HomePage