shiro-用户认证-连接数据库

Javase程序用shiro连接数据库验证用户身份

1、创建数据库

shiro-用户认证-连接数据库_第1张图片

2、导入jar包

版本要对好:

c3p0-0.9.2.1.jar

commons-beanutils-1.9.2.jar

commons-logging-1.2.jar

junit-4.10.jar

log4j-1.2.17.jar

mchange-commons-java-0.2.3.4.jar

mysql-connector-java-5.1.48.jar

shiro-all-1.2.3.jar

slf4j-api-1.7.7.jar

slf4j-log4j12-1.7.5.jar

3、新建shiro.ini

[main]

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource

dataSource.driverClass=com.mysql.jdbc.Driver

dataSource.jdbcUrl=jdbc:mysql://localhost:3306/myshiro

dataSource.user=root

dataSource.password=1234567

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

jdbcRealm.dataSource=$dataSource

securityManager.realm=$jdbcRealm

4、log4j.properties

log4j.rootLogger=error,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

5、JdbcRealmDemo.java

package com.pshdhx;

 

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.util.Factory;

import org.apache.shiro.mgt.SecurityManager;

import org.apache.shiro.subject.Subject;

 

public class JdbcRealmDemo {

    public static void main(String[] args) {

       Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

       SecurityManager securityManager = factory.getInstance();

       SecurityUtils.setSecurityManager(securityManager);

       Subject subject = SecurityUtils.getSubject();

       UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "11211");

       try {

           subject.login(token);

           if(subject.isAuthenticated()){

              System.out.println("验证通过");

           }

       } catch (AuthenticationException e) {

           System.out.println("验证失败");

       }

      

    }

}

 

开始运行java程序

结果:验证成功、验证失败;

 

你可能感兴趣的:(shiro)