场景

从实例入手学习Shiro与Web的整合:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/90140802

在上面已经实现整合Web的基础上实现 Shiro 自定义Realm,然后查询数据实现权限验证。

实现

数据库搭建

新建t_user表,用户表

新建t_role表,角色表

新建t_permission表,权限表

建立表的关联关系

t_user表的roleId就是t_role表的id,一对多的关系。

t_role表的id就是t_premission表的roleId,一对多的关系。

插入t_user表数据

插入t_role数据

插入t_permission数据

添加项目依赖

打开pom.xml,添加mysql的依赖

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency>

完整pom.xml代码

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.badao.shiro</groupId><artifactId>ShiroWeb</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>ShiroWeb Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><!-- 添加servlet支持 --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.1</version></dependency><!-- 添加jstl支持 --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- 添加日志支持 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><!-- 添加shiro支持 --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.4</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.2.4</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.12</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency></dependencies><build><finalName>ShiroWeb</finalName></build>
</project>

新建连接数据库工具类

在util包下新建Dbutil.java

package com.badao.util;import java.sql.Connection;
import java.sql.DriverManager;/*** 数据库工具类* @author**/
public class DbUtil {/*** 获取数据库连接* @return* @throws Exception*/public Connection getCon() throws Exception{Class.forName("com.mysql.jdbc.Driver");Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shirotest", "root", "123");return con;}/*** 关闭数据库连接* @param con* @throws Exception*/public void closeCon(Connection con)throws Exception{if(con!=null){con.close();}}public static void main(String[] args) {DbUtil dbUtil=new DbUtil();try {dbUtil.getCon();System.out.println("数据库连接成功");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println("数据库连接失败");}}
}

编写自定义Realm

新建realm包,包下新建MyRealm.java

package com.badao.realm;import java.sql.Connection;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;import com.badao.dao.UserDao;
import com.badao.entity.User;
import com.badao.util.DbUtil;public class MyRealm extends AuthorizingRealm{private UserDao userDao=new UserDao();private DbUtil dbUtil=new DbUtil();/*** 为当前登录的用户授予角色和权限*/@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {String userName=(String)principals.getPrimaryPrincipal();SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();Connection con=null;try{con=dbUtil.getCon();authorizationInfo.setRoles(userDao.getRoles(con,userName));authorizationInfo.setStringPermissions(userDao.getPermissions(con,userName));}catch(Exception e){e.printStackTrace();}finally{try {dbUtil.closeCon(con);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}return authorizationInfo;}/*** 验证当前登录的用户*/@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {String userName=(String)token.getPrincipal();Connection con=null;try{con=dbUtil.getCon();User user=userDao.getByUserName(con, userName);if(user!=null){AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");return authcInfo;}else{return null;}}catch(Exception e){e.printStackTrace();}finally{try {dbUtil.closeCon(con);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}}

编写UserDao

package com.badao.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;import com.badao.entity.User;public class UserDao {public User getByUserName(Connection con,String userName)throws Exception{User resultUser=null;String sql="select * from t_user where userName=?";PreparedStatement pstmt=con.prepareStatement(sql);pstmt.setString(1, userName);ResultSet rs=pstmt.executeQuery();if(rs.next()){resultUser=new User();resultUser.setId(rs.getInt("id"));resultUser.setUserName(rs.getString("userName"));resultUser.setPassword(rs.getString("password"));}return resultUser;}public Set<String> getRoles(Connection con, String userName) throws Exception{Set<String> roles=new HashSet<String>();String sql="select * from t_user u,t_role r where u.roleId=r.id and u.userName=?";PreparedStatement pstmt=con.prepareStatement(sql);pstmt.setString(1, userName);ResultSet rs=pstmt.executeQuery();while(rs.next()){roles.add(rs.getString("roleName"));}return roles;}public Set<String> getPermissions(Connection con, String userName)throws Exception {Set<String> permissions=new HashSet<String>();String sql="select * from t_user u,t_role r,t_permission p where u.roleId=r.id and p.roleId=r.id and u.userName=?";PreparedStatement pstmt=con.prepareStatement(sql);pstmt.setString(1, userName);ResultSet rs=pstmt.executeQuery();while(rs.next()){permissions.add(rs.getString("permissionName"));}return permissions;}}

编写entity

package com.badao.entity;public class User {private Integer id;private String userName;private String password;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}

修改ini配置文件

将原来的配置用户、角色、权限的部分替换为:

myRealm=com.badao.realm.MyRealm
securityManager.realms=$myRealm

完整配置文件代码

[main]
authc.loginUrl=/login
roles.unauthorizedUrl=/unauthorized.jsp
perms.unauthorizedUrl=/unauthorized.jspmyRealm=com.badao.realm.MyRealm
securityManager.realms=$myRealm[urls]
/login=anon
/admin/**=authc
/student=roles[teacher]
/teacher=perms["user:create"]

项目结构

源码下载

https://download.csdn.net/download/badao_liumang_qizhi/11174591

从实例入手学习Shiro自定义Realm实现查询数据进行验证相关推荐

  1. 从实例入手学习Shiro的会话机制

    场景 从实例入手学习Shiro与Web的整合: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/90140802 在上面已经实现整合 ...

  2. 从实例入手学习Shiro与Web的整合

    场景 Shiro官网关于Web整合文档: http://shiro.apache.org/web.html#Web-configuration W3Cschool Shiro Web集成: https ...

  3. Shiro验证策略-shiro自定义实现Realm来实现身份验证-shiro散列加密算法-shiro授权-shiro自定义Realm实现授权

    Shiro验证策略 Authentication Strategy:认证策略,在shiro中有三种认证策略: AtleastOneSuccessfulStrategy[默认] 如果一个或多个Realm ...

  4. shiro自定义Realm

    1.1 自定义Realm 上边的程序使用的是shiro自带的IniRealm,IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm. ...

  5. mysql查询数据为0的所有字段6_MySQL8.0 初级学习笔记(六)查询数据

    MySQL8.0 初级学习笔记(六)查询数据 MySQL8.0 初级学习笔记(六)查询数据 查询有多种方法:单表查询,使用集合函数查询,连接查询,子查询,合并查询结果,为表和字段取别名,使用正则表达式 ...

  6. Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证

    一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...

  7. Redis事务中的watch机制-从实例入手学习

    场景 Redis中事务的实现流程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/105048241 在上面学会Redis的事务的 ...

  8. Android布局管理器-从实例入手学习相对布局管理器的使用

    场景 AndroidStudio跑起来第一个App时新手遇到的那些坑: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103797 ...

  9. Jquery中进行post请求时同步与异步的区别(从实例入手学习)

    场景 表单中有两个输入框input在提交这个表单前需要对两个输入框进行校验. 即点击提交按钮时会经过校验的方法,此方法会post方式提交到后台,在请求后台成功后的回调方法中会对js变量进行赋值,进而决 ...

最新文章

  1. jQuery中的$.getJSON
  2. lenovo L480 进入bios_重装系统重启后不引导,重装系统无法进入引导
  3. python pip管理工具
  4. no ip domain-lookup 什么意思
  5. 几个超级实用但很少人知道的 VS 技巧[更新]
  6. 针对标签属性data-**的使用
  7. LeetCode 1139. 最大的以 1 为边界的正方形(DP)
  8. 对话框下的菜单使用setCheck
  9. 学习 | Spring Cloud Config 从入门到精通
  10. 柔性穿刺针有限元模型
  11. 针对业务系统的开发,如何做需求分析和设计1
  12. 喜庆博客积分排名进入前3万
  13. qt制作简单的图片处理器(只实现对图片进行添加文字)
  14. 《FLUENT 14流场分析自学手册》——1.4 流体运动及换热的多维方程组
  15. 代码实现利用inf文件安装硬件驱动
  16. Matlab关于转置与共轭转置
  17. 车企号脉,资本试药,出行服务带病也要上场
  18. 钛灵科技入驻中国视界,共筑人工智能视觉产业新高地
  19. 振荡次数计算机控制系统,计算机控制第四章.ppt
  20. 数据结构概述3 对称矩阵、树和二叉树

热门文章

  1. EasyExcel 2 上传 下载
  2. jq定制上传按钮,选择文件就上传
  3. 史上最详细阿里云服务器上Docker部署War包项目 实战每一步都带详细图解!!!
  4. 思源黑体ttf_模块模板 | 简单方法替换将TTF格式字体转换为Magisk模块
  5. redis数据持久化到mysql_Redis【数据持久化篇】
  6. 安装python环境与运行_专栏G|轻松学Python01:Python环境搭建与运行
  7. python语言格式化输出_Python | 格式化输出字符串
  8. asp.net session 如何知道是哪个浏览器客户端_微服务下的分布式session管理
  9. java调用sql返回list_Hibernate执行原生SQL返回ListMap类型结果集
  10. python中set和dict类型_python从菜鸟到小仙的成长之路-----Dict和Set类型篇