【Spring Boot】015-Shiro整合Mybatis

目录

一、整合Mybatis连接数据库

1、导入Maven依赖

2、创建配置文件application.yaml

3、编写配置文件application.properties

4、编写Account实体类

5、编写AccountMapper

6、编写AccountMapper.xml

7、编写AccountService接口

8、编写AccountService接口的实现类

9、写测试代码

10、测试结果

二、用户认证

1、修改AccountRealm,账号密码从数据库查询

2、测试结果


一、整合Mybatis连接数据库

1、导入Maven依赖

        <!--整合mybatis,连接数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

 

2、创建配置文件application.yaml

spring:
  datasource:
    username: root
    password: zibo15239417242
    url: jdbc:mysql://localhost:3306/zibo?serverTimezone=UTC
    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

 

3、编写配置文件application.properties

mybatis.type-aliases-package=com.zibo.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

 

4、编写Account实体类

package com.zibo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private Integer id;
    private String name;
    private Double money;
}

 

5、编写AccountMapper

package com.zibo.mapper;

import com.zibo.pojo.Account;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

//这个注解表示这是一个mybatis的mapper类
@Mapper
@Repository
public interface AccountMapper{

    List<Account> findAll();


}

 

6、编写AccountMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zibo.mapper.AccountMapper">
    <!--查询所有-->
    <!--这个地方用account需要在配置文件中设置别名,具体见配置文件-->
    <select id="findAll" resultType="Account">
        select * from account;
    </select>
</mapper>

 

7、编写AccountService接口

package com.zibo.service;

import com.zibo.pojo.Account;

import java.util.List;

public interface AccountService {
    List<Account> findAll();
}

 

8、编写AccountService接口的实现类

package com.zibo.service;

import com.zibo.mapper.AccountMapper;
import com.zibo.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountMapper accountMapper;

    @Override
    public List<Account> findAll() {
        return accountMapper.findAll();
    }
}

 

9、写测试代码

package com.zibo;

import com.zibo.pojo.Account;
import com.zibo.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class ShiroSpringBootApplicationTests {

    @Autowired
    AccountService accountService;

    @Test
    void contextLoads() {
        List<Account> all = accountService.findAll();
        for (Account account : all) {
            System.out.println(account);
        }
    }

}

 

10、测试结果

 

二、用户认证

1、修改AccountRealm,账号密码从数据库查询

package com.zibo.config;

import com.zibo.pojo.Account;
import com.zibo.service.AccountService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

//自定义的AccountRealm,需要继承AuthorizingRealm
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    AccountService accountService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法doGetAuthorizationInfo!");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证方法doGetAuthenticationInfo!");

        UsernamePasswordToken accountToken = (UsernamePasswordToken)authenticationToken;

        //我们这里不该这么写的,我们应该写一个通过用户名查询的方法,但是既然都写到这了,就这么写吧
        List<Account> all = accountService.findAll();
        String tokenUsername = accountToken.getUsername();
        boolean haveThisAccount = false;
        String password = null;
        for (Account account : all) {
            if(account.getName().equals(tokenUsername)){
                //说明存在这个用户名
                haveThisAccount = true;
                //我们假装其钱数就是其密码
                password = String.valueOf(account.getMoney());
                System.out.println(password);
                break;
            }
        }
        if(!haveThisAccount){
            return null;//抛出异常,用户名不存在
        }
        //密码认证,shiro做
        //可以加密:MD5加密,MD5盐值加密
        return new SimpleAuthenticationInfo("",password,"");
    }
}

 

2、测试结果

 

 

 

 

 

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页