shiro 整合Mybatis

Hanyta發表於2024-05-18
  • 就是將之前一步自己模擬的資料要換成從資料庫中查出來的真實資料
  1. 匯入mybatis相關依賴

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>xxx</version>
    </dependency>
    
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>xxx</version>
    </dependency>
    
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.3</version>
    </dependency>
    
  2. 配置檔案application.yml

    spring:
      datasource:
        username: root
        password: admin
        #?serverTimezone=UTC解決時區的報錯
        url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource # 匯入了就可以用自己匯入的資料庫連線池
    
        #Spring Boot 預設是不注入這些屬性值的,需要自己繫結
        #druid 資料來源專有配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
    
        #配置監控統計攔截的filters,stat:監控統計、log4j:日誌記錄、wall:防禦sql注入
        #如果允許時報錯  java.lang.ClassNotFoundException: org.apache.log4j.Priority
        #則匯入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
        
    mybatis:
      type-aliases-package: nuc.ss.pojo
      mapper-locations: classpath:mapper/*.xml
    
  3. 編寫真實的業務

  4. UserRealm連線真實資料庫

    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("執行了=>認證doGetAuthorizationInfo");
    
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        
        // 真實資料庫 使用者名稱、密碼, 資料中取
        User user = userService.queryUserByName(userToken.getUsername());
    
        if (user == null) {//沒有這個人
            return null;
        }
    
        // 密碼認證,shiro做,預設是SimpleCredentialsMatcher加密,可以自己設定加密函式
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
    

相關文章