欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot+Shiro+Redis+Mybatis-plus 實戰(zhàn)項目及問題小結(jié)

 更新時間:2021年04月25日 09:52:11   作者:jiachengren  
最近也是一直在保持學(xué)習(xí)課外拓展技術(shù),所以想自己做一個簡單小項目,于是就有了這個快速上手 Shiro 和 Redis 的小項目,說白了就是拿來練手調(diào)調(diào) API,然后做完后拿來總結(jié)的小項目,感興趣的朋友一起看看吧

前言

完整的源代碼已經(jīng)上傳到 CodeChina平臺上,文末有倉庫鏈接🤭

技術(shù)棧

  1. 前端

html
Thymleaf
Jquery

  1. 后端

SpringBoot
Shiro
Redis
Mybatis-Plus


需求分析

有 1 和 2 用戶,用戶名和密碼也分別為 1 和 2 ,1 用戶有增加和刪除的權(quán)限,2用戶有更新的權(quán)限,登錄的時候需要驗證碼并且需要緩存用戶的角色和權(quán)限,用戶登出的時候需要將緩存的認證和授權(quán)信息刪除。


數(shù)據(jù)庫E-R圖設(shè)計

其實就是傳統(tǒng)的 RBAC 模型,不加外鍵的原因是因為增加外鍵會造成數(shù)據(jù)庫壓力。

在這里插入圖片描述


數(shù)據(jù)庫腳本

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80021
 Source Host           : localhost:3306
 Source Schema         : spring-security

 Target Server Type    : MySQL
 Target Server Version : 80021
 File Encoding         : 65001

 Date: 23/04/2021 18:18:01
*/

create database if not exists `spring-security` charset=utf8mb4;

use `spring-security`;

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission`  (
  `permissionid` int NOT NULL AUTO_INCREMENT,
  `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `perm` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`permissionid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES (1, '/toUserAdd', 'user:add');
INSERT INTO `permission` VALUES (2, '/toUserUpdate', 'user:update');
INSERT INTO `permission` VALUES (3, '/toUserDelete', 'user:delete');

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role`  (
  `roleid` int NOT NULL AUTO_INCREMENT,
  `role` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`roleid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'student');
INSERT INTO `role` VALUES (2, 'parent');
INSERT INTO `role` VALUES (3, 'teacher');

-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission`  (
  `permissionid` int NOT NULL,
  `roleid` int NOT NULL,
  PRIMARY KEY (`permissionid`, `roleid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of role_permission
-- ----------------------------
INSERT INTO `role_permission` VALUES (1, 1);
INSERT INTO `role_permission` VALUES (2, 2);
INSERT INTO `role_permission` VALUES (3, 3);

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `userid` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `salt` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `status` int NULL DEFAULT 1,
  PRIMARY KEY (`userid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '1', 'a0c68c64557599483e99630ce4d2f30e', 'ainjee', 1);
INSERT INTO `user` VALUES (2, '2', '78fc06a914bcf261ed749952b0c9f67b', 'eeiain', 1);

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role`  (
  `userid` int NOT NULL,
  `roleid` int NOT NULL,
  PRIMARY KEY (`userid`, `roleid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES (1, 1);
INSERT INTO `user_role` VALUES (1, 3);
INSERT INTO `user_role` VALUES (2, 2);

SET FOREIGN_KEY_CHECKS = 1;

Shiro 與 Redis 整合學(xué)習(xí)總結(jié)

整合SpringBoot與Shiro與Redis,這里貼出整個 pom.xml 文件源碼,可以直接復(fù)制

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jmu</groupId>
    <artifactId>shiro_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shiro_demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.7.1</version>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.jmu.shiro_demo.ShiroDemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

        <!-- 資源目錄 -->
        <resources>
            <resource>
                <!-- 設(shè)定主資源目錄  -->
                <directory>src/main/java</directory>
                <!-- maven default生命周期,process-resources階段執(zhí)行maven-resources-plugin插件的resources目標處理主資源目下的資源文件時,只處理如下配置中包含的資源類型 -->
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <!-- maven default生命周期,process-resources階段執(zhí)行maven-resources-plugin插件的resources目標處理主資源目下的資源文件時,是否對主資源目錄開啟資源過濾 -->
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

2.自定義 Realm 繼承 AuthorizingRealm 實現(xiàn) 認證和授權(quán)兩個方法

package com.jmu.shiro_demo.shiro;

import com.jmu.shiro_demo.entity.Permission;
import com.jmu.shiro_demo.entity.Role;
import com.jmu.shiro_demo.entity.User;
import com.jmu.shiro_demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授權(quán)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        User user = userService.getUserByUserName(username);
        //1.動態(tài)分配角色
        List<Role> roles = userService.getUserRoleByUserId(user.getUserid());
        roles.stream().forEach(role -> {authorizationInfo.addRole(role.getRole());});
        //2.動態(tài)授權(quán)
        List<Permission> perms = userService.getUserPermissionsByUserId(user.getUserid());
        perms.stream().forEach(permission -> {authorizationInfo.addStringPermission(permission.getPerm());});
        return authorizationInfo;
    }

    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.獲取用戶名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = userService.getUserByUserName(username);
        if(ObjectUtils.isEmpty(user)) {
            return null;
        }
        return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), new MyByteSource(user.getSalt()),this.getName());
    }

}

3.編寫 ShiroConfig 配置
核心是配置 ShiroFilterFactoryBean,DefaultSecurityManager,UserRealm(這里的Realm是自定義的),ShiroDialect 是整合 shiro與thymleaf在前端使用 shiro 的標簽的拓展包,來源于 github 的開源項目。

依次關(guān)系為
ShiroFilterFactoryBean 中 set DefaultSecurityManager,
DefaultSecurityManager 中 set UserRealm,
UserRealm 中 set CacheManager 和 加密的算法
CacheManager 可以為 EhCacheManager 也可以為 RedisCacheManager,此項目整合 redis 的 緩存管理器

package com.jmu.shiro_demo.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.jmu.shiro_demo.entity.Permission;
import com.jmu.shiro_demo.service.PermissionService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Autowired
    private PermissionService permissionService;

    //1.配置ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 設(shè)置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /** 設(shè)置Shiro 內(nèi)置過濾器
         * anon: 無需認證(登陸)可以訪問
         * authc: 必須認證才可以訪問
         * user: 如果使用 rememberMe 的功能可以直接訪問
         * perms: 該資源必須得到資源權(quán)限才可以訪問
         * role: 該資源必須得到角色權(quán)限才可以訪問
        */
        Map<String ,String> filterMap = new LinkedHashMap<String ,String>();
        //配置頁面請求攔截
        filterMap.put("/index","anon");
        filterMap.put("/login","anon");
        filterMap.put("/getAuthCode","anon");
        //配置動態(tài)授權(quán)
        List<Permission> perms = permissionService.list();
        for (Permission permission : perms) {
            filterMap.put(permission.getUrl(),"perms["+permission.getPerm()+"]");
        }
        filterMap.put("/*","authc");
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    //2.配置DefaultSecurityManager
    @Bean(name = "securityManager")
    public DefaultSecurityManager defaultSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        defaultSecurityManager.setRealm(userRealm);
        return defaultSecurityManager;
    }

    //3.配置Realm
    @Bean(name = "userRealm")
    public UserRealm getRealm() {
        //1. 創(chuàng)建自定義的 userRealm 對象
        UserRealm userRealm = new UserRealm();
        //2. 設(shè)置 userRealm 的 CredentialsMatcher密碼校驗器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //2.1 設(shè)置加密算法
        matcher.setHashAlgorithmName("MD5");
        //2.2 設(shè)置散列次數(shù)
        matcher.setHashIterations(6);
        userRealm.setCredentialsMatcher(matcher);
        userRealm.setCacheManager(new RedisCacheManager());
        userRealm.setAuthenticationCachingEnabled(true); //認證
        userRealm.setAuthenticationCacheName("authenticationCache");
        userRealm.setAuthorizationCachingEnabled(true); //授權(quán)
        userRealm.setAuthorizationCacheName("authorizationCache");
        return userRealm;
    }

    //4.配置Thymleaf的Shiro擴展標簽
    @Bean
    public ShiroDialect getShiroDialect() {
        return new ShiroDialect();
    }
}

4.定義Shiro 加鹽的類

package com.jmu.shiro_demo.shiro;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.util.ByteSource;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;

/**
 * 解決:
 *  shiro 使用緩存時出現(xiàn):java.io.NotSerializableException:
 *  org.apache.shiro.util.SimpleByteSource
 *  序列化后,無法反序列化的問題
 */
public class MyByteSource implements ByteSource, Serializable {
    private static final long serialVersionUID = 1L;

    private byte[] bytes;
    private String cachedHex;
    private String cachedBase64;

    public MyByteSource(){
    }

    public MyByteSource(byte[] bytes) {
        this.bytes = bytes;
    }

    public MyByteSource(char[] chars) {
        this.bytes = CodecSupport.toBytes(chars);
    }

    public MyByteSource(String string) {
        this.bytes = CodecSupport.toBytes(string);
    }

    public MyByteSource(ByteSource source) {
        this.bytes = source.getBytes();
    }

    public MyByteSource(File file) {
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
    }

    public MyByteSource(InputStream stream) {
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
    }

    public static boolean isCompatible(Object o) {
        return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

    @Override
    public byte[] getBytes() {
        return this.bytes;
    }


    @Override
    public String toHex() {
        if(this.cachedHex == null) {
            this.cachedHex = Hex.encodeToString(this.getBytes());
        }
        return this.cachedHex;
    }

    @Override
    public String toBase64() {
        if(this.cachedBase64 == null) {
            this.cachedBase64 = Base64.encodeToString(this.getBytes());
        }

        return this.cachedBase64;
    }

    @Override
    public boolean isEmpty() {
        return this.bytes == null || this.bytes.length == 0;
    }
    @Override
    public String toString() {
        return this.toBase64();
    }

    @Override
    public int hashCode() {
        return this.bytes != null && this.bytes.length != 0? Arrays.hashCode(this.bytes):0;
    }

    @Override
    public boolean equals(Object o) {
        if(o == this) {
            return true;
        } else if(o instanceof ByteSource) {
            ByteSource bs = (ByteSource)o;
            return Arrays.equals(this.getBytes(), bs.getBytes());
        } else {
            return false;
        }
    }

    private static final class BytesHelper extends CodecSupport {
        private BytesHelper() {
        }

        public byte[] getBytes(File file) {
            return this.toBytes(file);
        }

        public byte[] getBytes(InputStream stream) {
            return this.toBytes(stream);
        }
    }

}

5.定義 RedisCacheManager

package com.jmu.shiro_demo.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

public class RedisCacheManager implements CacheManager {

    //參數(shù)1 :認證或者是授權(quán)緩存的統(tǒng)一名稱
    @Override
    public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
        System.out.println(cacheName);
        return new RedisCache<K,V>(cacheName);
    }

}

6.定義 RedisCache

package com.jmu.shiro_demo.shiro;

import com.jmu.shiro_demo.utils.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.util.Collection;
import java.util.Set;

@Slf4j
public class RedisCache<k,v> implements Cache<k,v> {

    private String cacheName;

    public RedisCache() {

    }

    public RedisCache(String cacheName) {
        this.cacheName = cacheName;
    }

    @Override
    public v get(k k) throws CacheException {
        System.out.println("get key:" + k);
        return (v) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
    }

    @Override
    public v put(k k, v v) throws CacheException {
        System.out.println("put key: " + k);
        System.out.println("put value: " + v);
        getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v);
        return v;
    }

    @Override
    public v remove(k k) throws CacheException {
        log.info("remove k:" + k.toString());
        return (v) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
    }

    @Override
    public void clear() throws CacheException {
        log.info("clear");
        getRedisTemplate().delete(this.cacheName);
    }

    @Override
    public int size() {
        return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
    }

    @Override
    public Set<k> keys() {
        return getRedisTemplate().opsForHash().keys(this.cacheName);
    }

    @Override
    public Collection<v> values() {
        return getRedisTemplate().opsForHash().values(this.cacheName);
    }

    public RedisTemplate getRedisTemplate() {
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBeanByBeanName("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}

核心Mapper文件

1.UserMapper.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.jmu.shiro_demo.mapper.UserMapper">

<!--這是 連接 5 張表的sql語句,根據(jù)用戶ID獲取到該用戶所擁有的權(quán)限,在這里寫出來,但是不使用,因為效率不高-->
    <select id="getUserPermissionsByUserId" parameterType="int" resultType="permission">
        select url,perm
            from user,user_role,role,role_permission,permission
        where user.userid = user_role.userid
            and user_role.roleid = role.roleid
            and role.roleid = role_permission.roleid
            and role_permission.permissionid = permission.permissionid
            and user.userid=#{userid};
    </select>

    <!--查出一個用戶所擁有的全部角色-->
    <select id="getUserRoleByUserId" parameterType="int" resultType="role">
        select role.roleid,role
            from user,user_role,role
        where user.userid = user_role.userid
              and user_role.roleid = role.roleid
              and user.userid = #{userId};
    </select>

</mapper>

2.RoleMapper.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.jmu.shiro_demo.mapper.RoleMapper">

    <!--查出一個角色所擁有的全部權(quán)限-->
    <select id="getRolePermissionsByRoleId" parameterType="int" resultType="permission">
        select url,perm
            from role,role_permission,permission
        where role.roleid = role_permission.roleid
            and role_permission.permissionid = permission.permissionid
            and role.roleid = #{roleId};
    </select>

</mapper>

項目完整代碼(CodeChina平臺)

shiro_demo


項目運行

在這里插入圖片描述


踩過的坑歸納

  1. Redis 反序列化的時候報錯 no valid constructor;
  2. 解決:MyByteSource 加鹽類實現(xiàn)的時候需要實現(xiàn)ByteSource接口,然后提供無參構(gòu)造方法
  3. 用戶退出的時候Redis中認證信息的緩存沒有刪除干凈
  4. 解決:UserRealm 的認證方法返回的第一個參數(shù)不要用 User實體對象,而是用 User 的 getUsername() 返回唯一標識用戶的用戶名,其他有用到 Principal 的時候獲得到的都是 這個 username。

相關(guān)文章

  • java 中ArrayList迭代的兩種實現(xiàn)方法

    java 中ArrayList迭代的兩種實現(xiàn)方法

    這篇文章主要介紹了java 中ArrayList迭代的兩種實現(xiàn)方法的相關(guān)資料,Iterator與for語句的結(jié)合,需要的朋友可以參考下
    2017-09-09
  • 如何解決java壓縮文件亂碼問題

    如何解決java壓縮文件亂碼問題

    在本篇文章中我們給大家分享的是一篇關(guān)于java壓縮文件亂碼問題的解決辦法,有需要的朋友們可以學(xué)習(xí)下。
    2019-12-12
  • Java經(jīng)典面試題最全匯總208道(五)

    Java經(jīng)典面試題最全匯總208道(五)

    這篇文章主要介紹了Java經(jīng)典面試題最全匯總208道(五),本文章內(nèi)容詳細,該模塊分為了六個部分,本次為第五部分,需要的朋友可以參考下
    2023-01-01
  • maven配置本地倉庫的方法步驟

    maven配置本地倉庫的方法步驟

    本文主要介紹了maven配置本地倉庫的方法步驟,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Java基于Calendar類輸出指定年份和月份的日歷代碼實例

    Java基于Calendar類輸出指定年份和月份的日歷代碼實例

    這篇文章主要介紹了Java 使用Calendar類輸出指定年份和月份的日歷,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • java讀取zip/jar包中文件的幾種方式

    java讀取zip/jar包中文件的幾種方式

    這篇文章主要給大家介紹了關(guān)于java讀取zip/jar包中文件的幾種方式,在我們?nèi)粘J褂弥袎嚎s文件是非常常用的,文中通過示例代碼將java讀取zip/jar包中文件的方法介紹的非常詳細,需要的朋友可以參考下
    2023-07-07
  • java數(shù)據(jù)結(jié)構(gòu)與算法數(shù)組模擬隊列示例詳解

    java數(shù)據(jù)結(jié)構(gòu)與算法數(shù)組模擬隊列示例詳解

    這篇文章主要為大家介紹了java數(shù)據(jù)結(jié)構(gòu)與算法數(shù)組模擬隊列示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • SpringBoot 關(guān)于Feign的超時時間配置操作

    SpringBoot 關(guān)于Feign的超時時間配置操作

    這篇文章主要介紹了SpringBoot 關(guān)于Feign的超時時間配置操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Maven繼承父工程時的relativePath標簽解析用法小結(jié)

    Maven繼承父工程時的relativePath標簽解析用法小結(jié)

    relativePath 的作用是為了找到父級工程的pom.xml,本文主要介紹了Maven繼承父工程時的relativePath標簽解析用法小結(jié),具有一定的參考價值,感興趣的可以了解一下
    2024-03-03
  • Java全面講解順序表與鏈表的使用

    Java全面講解順序表與鏈表的使用

    大家好,今天給大家?guī)淼氖琼樞虮砗玩湵?,我覺得順序表還是有比較難理解的地方的,于是我就把這一塊的內(nèi)容全部整理到了一起,希望能夠給剛剛進行學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)的人帶來一些幫助,或者是已經(jīng)學(xué)過這塊的朋友們帶來更深的理解,我們現(xiàn)在就開始吧
    2022-05-05

最新評論