一、shiro整合thymeleaf
1、导入thymeleaf整合shiro的依赖
<!--thymeleaf整合shiro-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
2、在shiro配置类里面注册Bean
//配置shiroDialect:用来整合shiro与thymeleaf
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
3、在html里导入命名空间,这样写起来有提示
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
二、实现根据访问者状态隐藏标签
shiro整合好thymeleaf之后,就可以在标签中使用 shiro: 了,有很多可以用,https://github.com/theborakompanioni/thymeleaf-extras-shiro上有许多介绍。
实现代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>这里是首页</h1>
<p th:text="${msg01}"></p>
<div shiro:notAuthenticated=""><!--没有登陆时显示login-->
<a th:href="@{/login}">login</a></br>
</div>
<a th:href="@{/user/add}">add</a>
<a th:href="@{/user/update}">update</a></br>
<div shiro:authenticated=""><!--登陆后显示logout-->
<a th:href="@{/logout}">logout</a>
</div>
</body>
</html>
三、shiro实现登出
利用currentUser.logout()就能实现登出,实现代码如下(在controller里实现):
@RequestMapping("/logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();//先获取当前用户对象
subject.logout();//再执行登出
return "redirect:/";
}