springboot-shiro:整合thymeleaf
1 引入thymeleaf-shiro整合依赖
pom.xml
<!--thymeleaf-shiro整合包--> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.1.0</version> </dependency>
2 配置一个shiro的Dialect,在ShiroConfig中增加一个Bean
src/main/java/com/lv/config/ShiroConfig.java
//整合ShiroDialect:用来整合shiro thymeleaf @Bean public ShiroDialect getShiroDialect(){ return new ShiroDialect(); }
3 修改首页
增加了三部分:
- 在头文件中加入了shiro的约束
- 添加了登录的链接,和通过 th:if 实现该链接是否显示的判断.
- 添加了通过 shiro:hasPermission 对add和update链接显示与否的判断
src/main/resources/templates/index.html
<!DOCTYPE html> <html lang="en" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首页</h1> <p th:text="${msg}"></p> <!--从session中判断值--> <div th:if="${session.loginUser == null}"> <a th:href="@{/toLogin}">登录</a> </div> <hr> <div shiro:hasPermission="user:add"> <a th:href="@{/user/add}">add</a> </div> <div shiro:hasPermission="user:update"> <a th:href="@{/user/update}">update</a> </div> </body> </html>
4 在UserRealm 添加存入用户信息的代码
在用户认证成功后,将用户信息放入session中
src/main/java/com/lv/config/UserRealm.java
//认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthorizationInfo"); UsernamePasswordToken userToken = (UsernamePasswordToken) token; //连接真实的数据库 User user = userService.queryUserByName(userToken.getUsername()); if (user == null){ //没有这个人 return null; //UnknownAccountException } //用户登录成功将用户信息存入session Subject currentSubject = SecurityUtils.getSubject(); Session session = currentSubject.getSession(); session.setAttribute("loginUser",user); //密码认证,交给shiro做(可以加密: MD5,MD5盐值加密) return new SimpleAuthenticationInfo(user,user.getPwd(),""); }
5 启动项目测试
访问首页,未登录状态下,显示了登录按钮,点击登录
跳转到了登陆页面,登录admin1用户
登录成功后,登录按钮消失,并且只显示add按钮,admin1用户只有访问add权限
再登录admin2用户,只显示了update按钮,admin2用户只有访问update权限
说明权限控制成功实现,thymeleaf语法生效了,shiro整合thymeleaf完成
分类:
springboot-study
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix