Shiro中的jdbcRealm工具类(2)

本文章续 Shiro入门案例(1) 

JdbcRealm的方式访问数据库,通过与数据库的连接,验证相应的登录用户与授权。

mysql数据库表

CREATE TABLE users(
    id BIGINT(30) PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(40),
    PASSWORD VARCHAR(40)
)

注意:数据库表必须是users

pom.xml依赖

<dependencies>
    <!--shiro依赖-->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.2.4</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.12</version>
    </dependency>

    <!--数据库连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.10</version>
    </dependency>

    <!--日志-->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>

    <!--mysql驱动包-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>
</dependencies>

jdbc_realm.ini

jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm

dataSource=com.alibaba.druid.pool.DruidDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
# mysql数据库表
dataSource.url=jdbc:mysql:///shiro-text
# mysql用户名
dataSource.username=root
# mysql密码
dataSource.password=root

jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm

Shiro_Realm_Dey02

package shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class Shiro_Realm_Dey02 {

    public static void main(String[] args) {
        //创建工厂类
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbc_realm.ini");
        //jdbc_realm.ini文件的数据
        SecurityManager securityManager = factory.getInstance();
        //获取当前用户
        SecurityUtils.setSecurityManager(securityManager);
        Subject user = SecurityUtils.getSubject();

        //通过usernamePasswordToken来模拟html/jsp传递过来的用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken("admin", "123");
        try {
            user.login(token);
            System.out.println("登录成功");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
        }
    }

}

直接通过mian方法启动项目就出结果了。

希望这边文章对您有帮助

 

 

 

 

本站资源除特别声明外,转载文章请声明文章出处
东泰博客 » Shiro中的jdbcRealm工具类(2)

发表评论