pom.xmljava
<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.lihua</groupId> <artifactId>shiro01</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>shiro01 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> <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.16</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> </dependencies> <build> <finalName>shiro01</finalName> </build> </project>
jdbc_realm.inimysql
[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_jdbc_realm dataSource.user=root dataSource.password=root jdbcRealm.dataSource=$dataSource securityManager.realms=$jdbcRealm
JdbcRealm.javasql
package test; import org.apache.shiro.SecurityUtils; 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 JdbcRealm { public static void main(String[] args) { //讀取配置文件,初始化SecurityManager工廠 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbc_realm.ini"); //獲取SecurityManager實例 SecurityManager securityManager = factory.getInstance(); //把SecurityManager綁定到SecurityUtils SecurityUtils.setSecurityManager(securityManager); //獲得當前執行的用戶 Subject subject = SecurityUtils.getSubject(); //建立token令牌 用戶名/密碼形式 UsernamePasswordToken token = new UsernamePasswordToken("test", "test"); try { //用戶登陸 subject.login(token); System.out.println("登陸成功"); } catch (Exception e) { e.printStackTrace(); System.out.println("登陸失敗"); } //用戶註銷 subject.logout(); } }
注意:數據庫的表必須叫: users 字段爲 id,userName, password
數據庫