本文主要是介绍Shiro HelloWorld (二)从数据库中获得数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1、创建users表,插入一条记录</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">2、工程结构如下:</span>
表:
3、pom.xml
<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.13</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.26</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency>
4、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/zqd
dataSource.user=root
dataSource.password=root
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm
5、JdbcRealmTest.java
package com.trekiz.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 JdbcRealmTest {public static void main(String[] args) {//获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbc_realm.ini");//获得SecurityManager实例SecurityManager securityManager =factory.getInstance();//绑定给SecurityUtils SecurityUtils.setSecurityManager(securityManager);//得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证) Subject currentUser = SecurityUtils.getSubject();UsernamePasswordToken token = new UsernamePasswordToken("zhang", "12456");try{currentUser.login(token);System.out.println("Succeed!");}catch(AuthenticationException e){e.printStackTrace();System.out.println("fail");}currentUser.logout();}}
这篇关于Shiro HelloWorld (二)从数据库中获得数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!