该笔记是基于上一篇Spring Boot 整合Shiro + Jsp的拓展,这里只列了thymeleaf相关的配置和修改,前面完整的笔记点我跳转
完整的代码已经上传github,点击进入
感谢 编程不良人 up主 提供的宝贵视频教程
6.1 引入相关依赖(其他基础依赖见上文)
<!--thymeleaf整合shiro标签-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<!--视图模板thymeleaf相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
6.2 在ShiroConfig类中配置Shiro方言
@Bean(name = "shiroDialect")
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
6.3 在Application.properties中配置相关信息(替换原Jsp相关配置,其余保持不变)
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.mvc.view.prefix=classpath:/templates/
6.4 在Resources资源目录下新建templates文件夹,存放Html页面
6.5 在对应的控制器内,设置页面的跳转
由于thymeleaf中,所有的页面跳转都需要经过controller。因此在一些页面的跳转上面,需要另外包装一个接口来实现。
以登录页面跳转注册页面为例:
-
首先需要引入thymeleaf的命名空间:xmlns:th=“http://www.thymeleaf.org”
-
在点我去注册标签处,不能再使用之前的直接跳转register.html方式。而是改为访问控制器再由控制器跳转指定页面。
@RequestMapping("registerview") public String register(){ return "register"; }
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
登录
<form th:action="@{/user/login}" method="post">
用户:<input name="username" type="text">
密码:<input name="password" type="password">
<input type="text" name="verifyCode"><img th:src="@{/user/getImage}" >
<input type="submit" value="登录">
<a th:href="@{/user/registerview}">点我去注册</a>
</form>
</body>
</html>
6.6 Shiro标签的使用
以index.html为例: 更多使用教程见官方说明:https://github.com/theborakompanioni/thymeleaf-extras-shiro
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at//thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>hello world</p>
<a th:href="@{/user/logout}">退出登录</a>
<ul>
<ul>
<span shiro:principal=""></span>
<span shiro:hasPermission="user:delete:*">
拥有删除权限
</span>
<span shiro:hasRole="user">拥有用户权限</span>
<span shiro:hasRole="admin">拥有管理员权限</span>
<span shiro:hasRole="admin2">拥有管理员2权限</span>
</ul>
<li>商品管理</li>
<li>价格管理</li>
</ul>
</body>
</html>