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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion>
<groupId>com.fjm</groupId>
<artifactId>shiro1</artifactId>
<version>0.0.-SNAPSHOT</version>
<build/> <dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.</version>
<scope>provided</scope>
</dependency> <!--c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.</version>
</dependency> <!--mysql-connector jdk8对应驱动6.0以上,jdk7/6对应驱动5.0以下-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.</version>
</dependency> <!-- commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency> </dependencies>
</project>
jdbc_realm.ini
[main]
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/shiro_db
dataSource.user=root
dataSource.password=
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm
testClass
public class JdbcTealmTest { public static void main(String[] args) {
//获得shiro工厂 【从数据库中获取用户名和密码和令牌中的比较】
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbc_realm.ini");
//获得工厂实例
SecurityManager securityManager = factory.getInstance();
//绑定securityManager到SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
//获得当前执行用户
Subject currentUser = SecurityUtils.getSubject();
//创建令牌
UsernamePasswordToken token = new UsernamePasswordToken("fengjunming", "");
try {
currentUser.login(token);
System.out.println("身份验证成功!!!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("身份验证失败!!!");
} } }