员工列表页面跳转
根据我们的需求,我们应当在主页点击customers的时候就显示员工列表页面,这个功能需要以下几个步骤:
1、首先我们将前端首页的侧边栏Customers改为员工管理
2、a链接添加请求
<a class="nav-link" th:href="@{/emps}">员工管理</a>
3、将list单独放在emp文件夹下
4、编写处理请求的controller
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@RequestMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("emps",employees);
return "emp/list";
}
}
我们启动项目,测试一下看是否能够跳转,我们只需要将数据渲染进去即可
但是这时发现了一个问题,侧边栏和顶部在首页和员工列表页面都相同,我们可以把它抽取出来实现代码的复用,可以有效避免前端代码十分庞大的弊端
我们可以利用thymeleaf为我们提供的公共页面元素抽取功能
Thymeleaf 公共页面元素抽取
步骤:
1、抽取公共片段 th:fragment 定义模板名
2、引入公共片段 th:insert 插入模板名
实现:
1、我们抽取头部nav标签,我们在dashboard中将nav部分定义一个模板名
<!-- 定义th:fragment="topbar" -->
<nav th:fragment="topbar" class="navbar navbar-dark sticky-top bg-dark ">
<!--后台主页显示登录用户的信息-->
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">
[[${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="#">Sign out</a>
</li>
</ul>
</nav>
2、然后我们在list页面中去引入,可以删掉原来的nav
<!--引入抽取的topbar-->
<!--模板名 : 会使用thymeleaf的前后缀配置规则进行解析
使用~{模板::标签名}-->
<div th:insert="~{dashboard::topbar}"></div>
3、启动再次测试,可以看到已经成功加载过来了!
说明:
除了使用insert插入,还可以使用replace替换,或者include包含,三种方式会有一些小区别,具体可以参考thymeleaf官方文档;
我们使用replace替换,可以解决div多余的问题
侧边栏也是同理
定义模板:
<nav th:fragment="sitebar" class="col-md-2 d-none d-md-block bg-light sidebar">
然后我们在list页面中去引入:
<div th:insert="~{dashboard::sitebar}"></div>
为了重用更清晰,我们建立一个commons文件夹,专门存放公共页面,将刚才复用的头部栏,侧边栏代码放到commons页面中
我们去页面中引入
<div th:replace="~{common/commons::topbar}"></div>
<div th:replace="~{common/commons::sidebar}"></div>
侧边栏激活问题
1、将首页的超链接地址改到项目中
2、我们在a标签中加一个判断,使用class改变标签的值
<a th:class="${active=='main.html'?'nav-link active':'nav-link'}" th:href="@{/main.html}">首页</a>
<a th:class="${active=='list.html'?'nav-link active':'nav-link'}" th:href="@{/emps}">员工管理</a>
3、修改请求链接
<div th:replace="~{common/commons::sidebar(active='main.html')}"></div>
<div th:replace="~{common/commons::sidebar(active='list.html')}"></div>
员工信息页面展示
现在我们来遍历我们的员工信息!顺便美化一些页面,增加添加,修改,删除的按钮
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2>员工名单</h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>邮箱</th>
<th>性别</th>
<th>部门</th>
<th>出生日期</th>
<!--我们还可以在显示的时候带一些操作按钮-->
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emps:${emps}">
<td th:text="${emps.getId()}"></td>
<td th:text="${emps.getLastName()}"></td>
<td th:text="${emps.getEmail()}"></td>
<td th:text="${emps.getGender()==0?'女':'男'}"></td>
<td th:text="${emps.department.getDepartmentName()}"></td>
<!--使用时间格式化工具-->
<td th:text="${#dates.format(emps.getBirth(),'yyyy-MM-dd')}"></td>
<td>
<button class="btn btn-sm btn-primary">编辑</button>
<button class="btn btn-sm btn-danger">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
显示全部员工实现!