今天遇到一个很奇怪的问题:
shiro与thymeleaf结合使用时,前台shiro标签没有生效。但我的配置都是正确的。标签却总是不生效。万般无奈下自己一顿乱操作。它就好了。估计是maven的缓存问题造成。或项目的缓存造成的原因。或者浏览器的缓存也是一个比较蛋疼的问题。
我先将maven clean了一下,有install,再rebuild project,shift+ctrl+delete清空了浏览器缓存。改了一下jar的版本。springboot的2.1.6.RELEASE该为2.1.5,重新导入maven,再切换为2.1.6RELEASE.重新导入。关闭ide,再重启运行项目。最后好使用了(不行的话可使用关机重启试一下)。—关于这种由各种缓存引发的古怪问题。排查的方式将上面的操作都试一下。如果还没有解决问题,那就可以排除缓存的因素了。
附上我的配置:
pom.xml的关键配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- thymeleaf对shiro的扩展坐标。即thymeleaf标签对shiro框架的支持-->
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
测试页面test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3 th:text="${msg}" style="color:red"></h3>
<div shiro:hasPermission="user:add">
<a href="/user/add">添加</a>
</div>
<div shiro:hasPermission="user:update">
<a href="/user/update">更新</a>
</div>
<a href="/user/toLogin">登录</a>
</body>
</html>
ShiroConfig类中的关键配置如下:
@Configuration
public class ShiroConfig {
/**
* 配置ShiroDialect,用于Shiro和thymeleaf标签配合使用
* @return
*/
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
}
测试结果如下:
未登录时:
只有添加权限的用户登陆成功后的页面显示结果如下: