shiro实例 环境准备 配置

这里展示的是使用maven工程的:
pom.xml

<properties>
    <!-- spring版本号 -->
    <spring.version>4.3.2.RELEASE</spring.version>
    <!-- log4j日志文件管理包版本 -->
    <log4j.version>1.2.17</log4j.version>
    <!-- junit版本号 -->
    <junit.version>4.12</junit.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.4.1</mybatis.version>
    <!-- aspectj -->
    <aspectj.version>1.8.9</aspectj.version>
    <!-- shiro版本 -->
    <shiro.version>1.2.4</shiro.version>
    <!-- druid 版本 -->
    <druid.version>1.1.2</druid.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- springmvc的依赖坐标 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
      <scope>runtime</scope>
    </dependency>

    <!-- mybatis/springmvc-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
      <scope>runtime</scope>
    </dependency>

    <!-- mysql驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.29</version>
    </dependency>

    <!-- 阿里数据连接池依赖 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <!-- 其中包含了众多的java网络编程的工具包 -->
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.1</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

    <!-- shiro -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>${shiro.version}</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.2</version>
      <scope>runtime</scope>
    </dependency>

  </dependencies>

web.xml

<!-- shiro filter shiro核心 -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilter</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

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

  <!-- Spring监听器 加载配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml,classpath:spring-shiro.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--<async-supported>true</async-supported>-->
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

spring.xml

<!-- 导入配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- druid 数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="maxActive" value="20" />
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxOpenPreparedStatements" value="20" />
    </bean>

    <!-- 扫描mybatis -->
    <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.zm.web_shiro.model" />
        <property name="mapperLocations" value="classpath:mapper/*Mapper.xml" />
    </bean>
    <!-- 扫描Mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zm.web_shiro.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 添加事务注解支持 -->
    <tx:annotation-driven transaction-manager="txManager"/>
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=用户名
jdbc.password=密码

spring-mvc.xml

 <!-- 使用spring组件扫描@controller -->
    <context:component-scan base-package="com.zm.web_shiro.web"/>
    <!-- 通过annotation-driven可以替代下边的处理器映射器和适配器 -->

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />-->
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

spring-shiro.xml

<!-- 会话管理器 -->
    <bean id="sessionManager"
          class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="globalSessionTimeout" value="1800000"/>
        <property name="deleteInvalidSessions" value="true"/>
        <property name="sessionValidationSchedulerEnabled" value="true" />
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
        <property name="sessionDAO" ref="sessionDAO" />
        <property name="sessionIdCookieEnabled" value="true" />
        <property name="sessionIdCookie" ref="sessionIdCookie" />
        <property name="cacheManager" ref="cacheManager" />
    </bean>

    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="sessionIdGenerator" ref="sessionIdGenerator" />
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache" />
    </bean>

    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    <!-- 会话验证调度器 -->
    <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
        <property name="interval" value="1800000" />
        <property name="sessionManager" ref="sessionManager" />
    </bean>

    <!-- 会话管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- 设置安全管理器的安全数据源为自定义的 Realm -->
        <!-- By default the servlet container sessions will be used.  Uncomment this line
            to use shiro's native sessions (see the JavaDoc for more): -->
        <property name="realm" ref="myRealm"/>
        <property name="sessionManager" ref="sessionManager"/>
        <property name="cacheManager" ref="cacheManager"/>
        <property name="rememberMeManager" ref="rememberMeManager" />
    </bean>

    <!-- 配置缓存管理器 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
    </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>

    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie" >
        <constructor-arg value="sid" />
        <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"/>
        <property name="maxAge" value="604800"/> <!--7天 -->
    </bean>

    <bean id="myRealm" class="com.zm.web_shiro.realm.CustomRealm">
       <!-- <property name="userService" ref="userService"/>-->
        <!-- 配置缓存相关 -->
        <!-- 启用缓存 -->
        <property name="cachingEnabled" value="true"/>
        <!-- 开启认证缓存-->
        <property name="authenticationCachingEnabled" value="true"/>
        <!-- 指定认证缓存的名字(与 ehcache.xml 中声明的相同) -->
        <property name="authenticationCacheName" value="authenticationCache"/>
        <!--开启授权缓存-->
        <property name="authorizationCachingEnabled" value="true"/>
        <!-- 指定授权缓存的名字(与 ehcache.xml 中声明的相同) -->
        <property name="authorizationCacheName" value="authorizationCache"/>
    </bean>

    <!-- 自定义filter -->
    <bean id="VcodeControlFilter" class="com.zm.web_shiro.web.filter.VcodeControlFilter" />
    <bean id="accessControlFilter" class="com.zm.web_shiro.web.filter.CustomAccessControlFilter" />
    <bean id="KickoutSessionControlFilter" class="com.zm.web_shiro.web.filter.KickoutSessionControlFilter" >
        <property name="sessionManager" ref="sessionManager"/>
        <property name="cacheManager" ref="cacheManager"/>
        <property name="kickoutAfter" value="false"/>
        <property name="maxSession" value="1"/>
        <property name="kickoutUrl" value="/jsp/login.jsp?kickout=1"/>
    </bean>

    <bean id="userService" class="com.zm.web_shiro.service.impl.UserServiceImpl" />
    <!-- Shiro生命周期处理器 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!-- 此处名字需与web.xml中相同 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/jsp/login.jsp"/>
        <property name="unauthorizedUrl" value="/jsp/unauthorized.jsp"/>
        <property name="filterChainDefinitions">
            <value>
                /index.jsp = anon
                /unauthorized.jsp = anon
                /jsp/login.jsp = anon
                /jsp/admin.jsp = authc,KickoutSessionControlFilter
                /jsp/user.jsp = user,KickoutSessionControlFilter
                /login/doLogout = logout
                /login/code = VcodeControlFilter
                /login/** = accessControlFilter
                /jsp/** = user,KickoutSessionControlFilter
                <!-- 资源 -->
                /css/** = anon
                /js/** = anon
            </value>
        </property>
        <property name="filters">
            <map>
                <entry key="accessControlFilter" value-ref="accessControlFilter" />
                <entry key="KickoutSessionControlFilter" value-ref="KickoutSessionControlFilter" />
                <entry key="VcodeControlFilter" value-ref="VcodeControlFilter" />
            </map>
        </property>
    </bean>

ehcache-shiro.xml

<ehcache>
    <!--diskStore:缓存数据持久化的目录 地址  -->
    <diskStore path="E:\cache\ehcache" />
    <!--<diskStore path="java.io.tmpdir"/>--> <!-- 系统的默认临时文件路径 -->
    <defaultCache
            maxElementsInMemory="10000"
            maxElementsOnDisk="10000000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
    <!-- 登录记录缓存 锁定10分钟 -->
    <cache name="passwordRetryCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <!-- 并发登陆,管理会话缓存 -->
    <cache name="shiro-activeSessionCache" eternal="false"
           maxElementsInMemory="10000"
           overflowToDisk="true"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0"/>
    <!-- 授权缓存 -->
    <cache name="authenticationCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <!-- 认证缓存 -->
    <cache name="authorizationCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="3600"
           overflowToDisk="false"
           statistics="true">
    </cache>
</ehcache>

log4j.properties

#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=system.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式 %d [%t]%-5p [%c] - %m%n
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = e:/logs/web_shiro.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值