9159金沙游艺场-奥门金沙游艺场-[欢迎您]

9159金沙游艺场为您呈现最新的面貌!,目前注册送体验金,欢迎您将成为影视娱乐行业新的风向标,是亚洲的优质娱乐先锋。

Redis实现后台管理项目

日期:2019-10-07编辑作者:前端

基于Maven+SSM整合shiro+Redis实现后台管理项目,mavenredis

本项目由卖咸鱼叔叔开发完成,欢迎大神指点,慎重抄袭!参考了sojson提供的demo,和官方文档介绍。完整实现了用户、角色、权限CRUD及分页,还有shiro的登录认证+授权访问控制。

项目架构:Maven + SpringMVC + Spring + Mybatis + Shiro + Redis
数据库:MySql

前端框架:H-ui

 

首先创建Maven项目

1.pom.xml 加入依赖包

<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 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sys</groupId>
  <artifactId>sys</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sys Maven Webapp</name>
  <url>http://maven.apache.org</url>

        <dependencies>
            <!-- spring依赖管理 -->
            <!-- spring-context 是使用spring的最基本的环境支持依赖,会传递依赖core、beans、expression、aop等基本组件,以及commons-logging、aopalliance -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>

            <!-- spring-context-support 提供了对其他第三方库的内置支持,如quartz等 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>

            <!-- spring-orm 是spring处理对象关系映射的组件,传递依赖了jdbc、tx等数据库操作有关的组件 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>

            <!-- spring-webmvc 是spring处理前端mvc表现层的组件,也即是springMVC,传递依赖了web等web操作有关的组件 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>

            <!-- spring-aspects 增加了spring对面向切面编程的支持,传递依赖了aspectjweaver -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>4.3.2.RELEASE</version>
            </dependency>


            <!-- json解析, springMVC 需要用到 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.6.0</version>
            </dependency>

            <!-- mybatis依赖管理 -->
            <!-- mybatis依赖 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.3.0</version>
            </dependency>

            <!-- mybatis和spring整合 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.2.3</version>
            </dependency>

            <!-- mybatis 分页插件 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>4.1.6</version>
            </dependency>

            <!-- mysql驱动包依赖 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.37</version>
            </dependency>

            <!-- c3p0依赖 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5</version>
            </dependency>

            <!-- redis java客户端jar包 -->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>

            <!-- 文件上传 -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>

            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.5</version>
            </dependency>

            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-email</artifactId>
                <version>1.4</version>
            </dependency>

            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
                <version>2.7</version>
            </dependency>

            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.2</version>
            </dependency>

            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>4.4.4</version>
            </dependency>


            <!-- junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
            </dependency>

            <!-- servlet依赖 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.1.0</version>
                <scope>provided</scope>
            </dependency>
            <!-- jsp依赖 -->
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
            <!-- jstl依赖 -->
            <dependency>
                <groupId>org.glassfish.web</groupId>
                <artifactId>jstl-impl</artifactId>
                <version>1.2</version>
                <exclusions>
                    <exclusion>
                        <groupId>javax.servlet</groupId>
                        <artifactId>servlet-api</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>javax.servlet.jsp</groupId>
                        <artifactId>jsp-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>


        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>   


        <!-- shiro依赖包 --> 
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-core</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-spring</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-cas</artifactId>  
            <version>1.2.3</version>  
            <exclusions>  
                <exclusion>  
                    <groupId>commons-logging</groupId>  
                    <artifactId>commons-logging</artifactId>  
                </exclusion>  
            </exclusions>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-web</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-ehcache</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-quartz</artifactId>  
            <version>1.2.3</version>  
        </dependency> 
        <!-- shiro end -->             


        </dependencies>

     <build>
        <finalName>sys</finalName>
        <plugins>
            <!-- 指定JDK编译版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>  
                <configuration>  
                  <source>1.8</source>
                  <target>1.8</target>
                </configuration> 
            </plugin>
        </plugins>
    </build>

</project>

2.SSM框架配置

9159金沙游艺场,beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd  
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>  
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sys_test?characterEncoding=UTF8&amp;allowMultiQueries=true"/>
        <property name="user" value="root"/>  
        <property name="password" value="root"/>  
        <property name="maxPoolSize" value="100"/>  
        <property name="minPoolSize" value="10"/>  
        <property name="maxIdleTime" value="60"/>  
    </bean>

    <!-- mybatis 的 sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!-- mybatis mapper接口自动扫描、自动代理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.sys.mapper" />
    </bean>

    <!-- 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 事务传播行为 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="page*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="is*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
        </tx:attributes>
    </tx:advice>

    <!-- 织入事务增强功能 -->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.sys.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    </aop:config>

     <!-- 配置扫描spring注解(@Component、@Controller、@Service、@Repository)时扫描的包,同时也开启了spring注解支持 -->
     <!-- 这个地方只需要扫描service包即可,因为controller包由springMVC配置扫描,mapper包由上面的mybatis配置扫描 -->
    <context:component-scan base-package="com.sys.service"></context:component-scan>

    <!-- 开启spring aop 注解支持,要想aop真正生效,还需要把切面类配置成bean -->
    <aop:aspectj-autoproxy/>



</beans>                            

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd  
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 配置扫描spring注解时扫描的包,同时也开启了spring注解支持 -->
    <context:component-scan base-package="com.sys" />

    <!-- 开启springMVC相关注解支持 -->
    <mvc:annotation-driven />

    <!-- 开启spring aop 注解支持 -->
    <aop:aspectj-autoproxy/>


    <!-- 约定大于配置:约定视图页面的全路径 = prefix + viewName + suffix -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


    <!-- 文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxInMemorySize" value="40960" />
    </bean>

    <!-- 资源映射 -->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/skin/" mapping="/skin/**" />
    <mvc:resources location="/lib/" mapping="/lib/**" />


</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- 使用log4j2作为日志实现 -->
        <setting name="logImpl" value="LOG4J2"/>
    </settings>

    <typeAliases>
        <!-- 为指定包下的pojo类自动起别名 -->
        <package name="com.sys.pojo"/>
    </typeAliases>

    <mappers>
        <!-- 自动加载指定包下的映射配置文件 -->
        <package name="com.sys.mapper"/>
    </mappers>

</configuration>

Log4j2.xml 

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE xml>
<Configuration status="OFF">
    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{0} - %msg%n" />
        </Console>
        <RollingFile name="ROLLING" fileName="/logs/ups-manager/log.log"
             filePattern="/logs/log_%d{yyyy-MM-dd}_%i.log">
            <PatternLayout pattern="%d %p %c{1.} [%t] %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true" interval="1"/>
                <SizeBasedTriggeringPolicy size="1024 KB"/>
            </Policies>
            <DefaultRolloverStrategy max="100"/>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="CONSOLE" />
            <AppenderRef ref="ROLLING"/>
        </Root>

        <!-- 控制某些包下的类的日志级别 -->
        <Logger name="org.mybatis.spring" level="error">
            <AppenderRef ref="CONSOLE"/>
        </Logger>
    </Loggers>
</Configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

    <!-- 初始化spring容器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>  

    <!-- 设置post请求编码和响应编码 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        <init-param>
            <!-- 为true时也对响应进行编码 -->
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!-- 设置为/*时才会拦截所有请求,和servlet有点区别,servlet设置为/*只拦截所有的一级请求,如/xx.do,而不拦截/xx/xx.do;servlet设置为/时才会拦截所有请求 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring-shiro.xml,
            classpath:beans.xml,
            classpath:dispatcher-servlet.xml
        </param-value>
    </context-param>


    <!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

      <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>  


    <!-- 初始化springMVC容器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

3.实现用户、角色、权限页面操作功能,这里就不贴代码了

4.接下来就是shiro,登录认证和授权只需要继承AuthorizingRealm,其继承了 AuthenticatingRealm(即身份验证),而且也间接继承了 CachingRealm(带有缓存实现)。身份认证重写doGetAuthenticationInfo方法,授权重写doGetAuthorizationInfo方法。

9159金沙游艺场 1Shiro 默认提供的 Realm

 

身份认证流程

9159金沙游艺场 2

 

流程如下:

 代码实现:

/**
 * 
 */
package com.sys.shiro;


import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import com.sys.pojo.AdminUser;
import com.sys.service.AdminUserService;

/**  
* @ClassName: MyRealm  
* @Description: shiro 认证 + 授权   重写 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    AdminUserService adminUserService;


    /* (non-Javadoc)
     * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
     */
    /**
     * 授权Realm
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String account = (String)principals.getPrimaryPrincipal();
        AdminUser pojo = new AdminUser();
        pojo.setAccount(account);
        Long userId = adminUserService.selectOne(pojo).getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        /**根据用户ID查询角色(role),放入到Authorization里.*/
        info.setRoles(adminUserService.findRoleByUserId(userId));
        /**根据用户ID查询权限(permission),放入到Authorization里.*/
        info.setStringPermissions(adminUserService.findPermissionByUserId(userId));
        return info; 
    }

    /* (non-Javadoc)
     * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
     */
    /**
     * 登录认证Realm
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        String username = (String)token.getPrincipal();
        String password = new String((char[])token.getCredentials());
        AdminUser user = adminUserService.login(username, password);
        if(null==user){
            throw new AccountException("帐号或密码不正确!");
        }
        if(user.getIsDisabled()){
            throw new DisabledAccountException("帐号已经禁止登录!");
        }
        //**密码加盐**交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
        return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(),ByteSource.Util.bytes("3.14159"), getName());
    }


    /**
     * 清空当前用户权限信息
     */
    public  void clearCachedAuthorizationInfo() {
        PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
    /**
     * 指定principalCollection 清除
     */
    public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }


}

shiro的配置:

spring-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!--shiro 核心安全接口  -->
        <property name="securityManager" ref="securityManager"></property>
        <!--登录时的连接  -->
        <property name="loginUrl" value="/login"></property>       
        <!--未授权时跳转的连接  -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
           <!-- 其他过滤器 -->
           <property name="filters">
               <map>
                   <!-- <entry key="rememberMe" value-ref="RememberMeFilter"></entry> -->
                   <entry key="kickout" value-ref="KickoutSessionControlFilter"/>
               </map>
           </property>

        <!-- 读取初始自定义权限内容-->
        <!-- 如果使用authc验证,需重写实现rememberMe的过滤器,或配置formAuthenticationFilter的Bean -->
        <property name="filterChainDefinitions">
            <value>
                /js/**=anon
                /css/**=anon
                /images/**=anon
                /skin/**=anon
                   /lib/**=anon
                   /nodel/**=anon
                   /WEB-INF/jsp/**=anon
                   /adminUserLogin/**=anon



                   /**/submitLogin.do=anon
                /**=user,kickout
            </value>
        </property>
    </bean>




    <!-- Shiro生命周期处理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="MyRealm"/>
        <property name="rememberMeManager" ref="rememberMeManager"/>
    </bean>

    <bean id="MyRealm" class="com.sys.shiro.MyRealm" >
        <property name="cachingEnabled" value="false"/>
    </bean>

    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
        <property name="arguments" ref="securityManager"/>
    </bean>

    <!-- sessionIdCookie:maxAge=-1表示浏览器关闭时失效此Cookie -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
        <constructor-arg value="rememberMe"/>  
        <property name="httpOnly" value="true"/>  
        <property name="maxAge" value="-1"/>  
    </bean>

    <!-- 用户信息记住我功能的相关配置 -->
    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="rememberMe"/>
        <property name="httpOnly" value="true"/>
        <!-- 配置存储rememberMe Cookie的domain为 一级域名        这里如果配置需要和Session回话一致更好。-->
        <property name="maxAge" value="604800"/><!-- 记住我==保留Cookie有效7天 -->
    </bean>

    <!-- rememberMe管理器 -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)-->
        <property name="cipherKey"
                  value="#{T(org.apache.shiro.codec.Base64).decode('3AvVhmFLUs0KTA3Kprsdag==')}"/>
        <property name="cookie" ref="rememberMeCookie"/>
    </bean>

    <!-- 记住我功能设置session的Filter -->
    <bean id="RememberMeFilter" class="com.sys.shiro.RememberMeFilter" />

    <!-- rememberMeParam请求参数是 boolean 类型,true 表示 rememberMe -->
    <!-- shiro规定记住我功能最多得user级别的,不能到authc级别.所以如果使用authc,需打开此配置或重写实现rememberMe的过滤器 -->
    <!-- <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
        <property name="rememberMeParam" value="rememberMe"/>
    </bean> -->    

    <bean id="KickoutSessionControlFilter" class="com.sys.shiro.KickoutSessionControlFilter">
    </bean>


</beans>

5.登录即密码失败多次后锁定

/**
 * 
 */
package com.sys.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sys.pojo.AdminUser;
import com.sys.service.AdminUserService;
import com.sys.common.JedisUtils;
import com.sys.shiro.ShiroUtils;


/**  
* @ClassName: LoginController  
* @Description: 登录
*/
@Controller
public class LoginController{
    protected final static Logger logger = LogManager.getLogger(LoginController.class);
    protected Map<String, Object> resultMap = new LinkedHashMap<String, Object>();

    @Resource
    AdminUserService adminUserService;

    /**
    * @Description: 登录认证
    * @param um 登录账号
    * @param pw 登录密码
    * @param rememberMe 记住我
    * @param request
    * @return
    * @throws  
    * @author lao
    * @Date 2018年1月15日下午12:24:19
    * @version 1.00
     */
    @RequestMapping(value="/submitLogin.do",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> submitLogin(String um,String pw,boolean rememberMe,HttpServletRequest request){        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(um,ShiroUtils.getStrByMD5(pw));                     
        try{           
            token.setRememberMe(rememberMe);
            subject.login(token);
            JedisUtils.del(um);
            logger.info("------------------身份认证成功-------------------");
            resultMap.put("status", 200);
            resultMap.put("message", "登录成功!");
        } catch (DisabledAccountException dax) {  
            logger.info("用户名为:" + um + " 用户已经被禁用!");
            resultMap.put("status", 500);
            resultMap.put("message", "帐号已被禁用!");
        } catch (ExcessiveAttemptsException eae) {  
            logger.info("用户名为:" + um + " 用户登录次数过多,有暴力破解的嫌疑!");
            resultMap.put("status", 500);
            resultMap.put("message", "登录次数过多!");
        } catch (AccountException ae) {  
            logger.info("用户名为:" + token.getPrincipal() + " 帐号或密码错误!");
            String excessiveInfo = ExcessiveAttemptsInfo(um);
            if(null!=excessiveInfo){
                resultMap.put("status", 500);
                resultMap.put("message", excessiveInfo);
            }else{
                resultMap.put("status", 500);
                resultMap.put("message", "帐号或密码错误!");
            }
        } catch (AuthenticationException ae) {  
            logger.error(ae);
            logger.info("------------------身份认证失败-------------------");
            resultMap.put("status", 500);
            resultMap.put("message", "身份认证失败!");
        } catch (Exception e) { 
            logger.error(e);
            logger.info("未知异常信息。。。。");  
            resultMap.put("status", 500);
            resultMap.put("message", "登录认证错误!");
        }
        return resultMap;
    }


    /**
    * @Description: 退出
    * @return
    * @throws  
    * @author lao
    * @Date 2018年1月11日下午4:23:35
    * @version 1.00
     */
    @RequestMapping(value="logout",method=RequestMethod.GET)
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            logger.error("errorMessage:" + e.getMessage());
        }
        return "redirect:login";
    }


    /**
    * @Description: 验证器,增加了登录次数校验功能
    * @param um 登录账号
    * @throws  
    * @author lao
    * @Date 2018年1月15日下午12:03:18
    * @version 1.00
     */
    public String ExcessiveAttemptsInfo(String account){
        String excessiveInfo = null;
        StringBuffer userName = new StringBuffer(account);
        userName.append("ExcessiveCount");
        String accountKey = userName.toString();

        if(null == JedisUtils.get(accountKey)){
            JedisUtils.setex(accountKey, 1800, "1");
        }else{
            int count = Integer.parseInt(JedisUtils.get(accountKey))+1;
            JedisUtils.setex(accountKey, 1800-(120*count), Integer.toString(count));
        }
        /**登录错误5次,发出警告*/
        if(Integer.parseInt(JedisUtils.get(accountKey))==5){
            excessiveInfo = "账号密码错误5次,再错5次账号将被禁用!";
        }
        /**登录错误10次,该账号将被禁用*/
        if(Integer.parseInt(JedisUtils.get(accountKey))==10){
            AdminUser pojo = new AdminUser();
            pojo.setAccount(account);
            AdminUser au = adminUserService.selectOne(pojo);
            if(null!=au){
                adminUserService.updateDisabled(au.getId(), true);
            }
            JedisUtils.del(account);
            excessiveInfo = "账号密码错误过多,账号已被禁用!";
        }
        return excessiveInfo;
    }

}

6.并发登录控制

/**
 * 
 */
package com.sys.shiro;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.sys.common.JedisUtils;



/**  
* @ClassName: KickoutSessionControlFilter  
* @Description: 并发登录控制过滤器
* @author lao  
* @date 2018年1月15日下午2:54:42  
* @version 1.00 
*/
public class KickoutSessionControlFilter extends AccessControlFilter {

    protected final static Logger logger = LogManager.getLogger(KickoutSessionControlFilter.class);
    //踢出状态,true标示踢出
    final static String KICKOUT_STATUS = KickoutSessionControlFilter.class.getCanonicalName()+ "_kickout_status";    

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
            ServletResponse response, Object mappedValue) throws Exception {

        HttpServletRequest httpRequest = ((HttpServletRequest)request);
        String url = httpRequest.getRequestURI();
        Subject subject = getSubject(request, response);
        //如果是相关目录 or 如果没有登录 就直接return true
        if(url.startsWith("/open/") || (!subject.isAuthenticated() && !subject.isRemembered())){
            return Boolean.TRUE;
        }
        Session session = subject.getSession();
        Serializable sessionId = session.getId();
        /**
         * 判断是否已经踢出
         * 1.如果是Ajax 访问,那么给予json返回值提示。
         * 2.如果是普通请求,直接跳转到登录页
         */
        Boolean marker = (Boolean)session.getAttribute(KICKOUT_STATUS);
        if (null != marker && marker ) {
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断是不是Ajax请求
            if (ShiroUtils.isAjax(request) ) {
                logger.debug("当前用户已经在其他地方登录,并且是Ajax请求!");
                resultMap.put("user_status", "300");
                resultMap.put("message", "您已经在其他地方登录,请重新登录!");
                ShiroUtils.out(response, resultMap);
            }
            return  Boolean.FALSE;
        }



        //获取用户账号
        String userName = (String)subject.getPrincipal();

        //从缓存获取用户-Session信息 <userName,SessionId>
        String jedisSessionId = JedisUtils.get(userName);

        //如果已经包含当前Session,并且是同一个用户,跳过。
        if(null!=jedisSessionId && jedisSessionId.equals((String)sessionId)){
            //更新存储到缓存1个小时(这个时间最好和session的有效期一致或者大于session的有效期)
            JedisUtils.setex(userName,3600, (String)sessionId);
            return Boolean.TRUE;
        }
        //如果用户相同,Session不相同,那么就要处理了
        /**
         * 如果用户Id相同,Session不相同
         * 1.获取到原来的session,并且标记为踢出。
         * 2.继续走
         */
        if(null!=jedisSessionId && !jedisSessionId.equals((String)sessionId)){
            //标记session已经踢出
            session.setAttribute(KICKOUT_STATUS, Boolean.TRUE);
            //存储到缓存1个小时(这个时间最好和session的有效期一致或者大于session的有效期)
            JedisUtils.setex(userName, 3600, (String)sessionId);
            return  Boolean.TRUE;
        }

        if(null==jedisSessionId){
            //存储到缓存1个小时(这个时间最好和session的有效期一致或者大于session的有效期)
            JedisUtils.setex(userName, 3600, (String)sessionId);
        }
        return Boolean.TRUE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request,
            ServletResponse response) throws Exception {

        //先退出,这一步才是正常清除Session
        Subject subject = getSubject(request, response);
        subject.logout();
        WebUtils.getSavedRequest(request);
        //再重定向
        WebUtils.issueRedirect(request, response,"/login");
        return false;
    }    



}

以上为核心代码只做参考,可自行下载项目部署运行。运行前请确认好环境,并根据resources/readme.rd文档介绍操作

如有缺陷,大神勿喷,欢迎留言指点!

项目下载链接:

Redis 下载:

解压后直接运行 redis-server.exe 启动服务即可。

本项目由卖咸鱼叔叔开发完成,欢迎大神指点,慎重抄袭!参考了sojson提供的demo,和...

本文由9159金沙游艺场-奥门金沙游艺场-[欢迎您]发布于前端,转载请注明出处:Redis实现后台管理项目

关键词:

java基础学习

Java基础学习(一),java基础学习 JAVA专业方法       源程序(myProgram.java) – 编译(javac myProgram.java) -JAVA字节码(myPr...

详细>>

VS2013编译FFmpeg9159金沙游艺场

由于毕设需要开始学习ffmpeg,因为要修改源码所以这里只能是源码编译。如果要直接使用ffmpeg网上有现成的SDK。源码...

详细>>

模拟斗地主的洗牌发放营业牌照

Java学习笔记34(会集框架八:综合案例:模拟斗地主的洗牌发放营业牌照),学习笔记洗牌 规则: 1.54张扑克牌,有...

详细>>

Python数据分析工具安装集合

用python做数据分析离不开几个好的轮子(或称为科学棧/第三方包等),比如matplotlib,numpy,scipy, pandas, scikit-learn,gens...

详细>>