• 04.shiro会话管理


    目录

    1.会话管理

    2.ehcache.xml的配置文件

    3.授权使用缓存


    1.会话管理

    shiro里面新建一个类ShiroSessionListener 实现SessionListener3个方法

    1. package com.hz.ssm.shiro;
    2. import org.apache.shiro.session.Session;
    3. import org.apache.shiro.session.SessionListener;
    4. /**
    5. * @author黄仲
    6. * @site www.Hz.com
    7. * @company 公司
    8. * @create 2022-08-29 8:31
    9. */
    10. public class ShiroSessionListener implements SessionListener {
    11. @Override
    12. public void onStart(Session session) {
    13. System.out.println("ShiroSessionListener.onstart..."+session.getId());
    14. }
    15. @Override
    16. public void onStop(Session session) {
    17. System.out.println("ShiroSessionListener.onStop..."+session.getId());
    18. }
    19. @Override
    20. public void onExpiration(Session session) {
    21. System.out.println("ShiroSessionListener.onExpiration..."+session.getId());
    22. }
    23. }

    然后到shiro.xml里面配置  稍微修改

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="shiroRealm" class="com.hz.ssm.shiro.MyRealm">
    6. <property name="userBiz" ref="userBiz" />
    7. <property name="credentialsMatcher">
    8. <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    9. <property name="hashAlgorithmName" value="md5"/>
    10. <property name="hashIterations" value="1024"/>
    11. <property name="storedCredentialsHexEncoded" value="true"/>
    12. bean>
    13. property>
    14. bean>
    15. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    16. <property name="realm" ref="shiroRealm" />
    17. <property name="sessionManager" ref="sessionManager">property>
    18. bean>
    19. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    20. <property name="securityManager" ref="securityManager" />
    21. <property name="loginUrl" value="/login"/>
    22. <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
    23. <property name="filterChainDefinitions">
    24. <value>
    25. /user/login=anon
    26. /user/updatePwd.jsp=authc
    27. /admin/*.jsp=roles[4]
    28. /user/teacher.jsp=perms[2]
    29. value>
    30. property>
    31. bean>
    32. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    33. <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
    34. bean>
    35. <bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
    36. <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    37. bean>
    38. <bean id="shiroSessionListener" class="com.hz.ssm.shiro.ShiroSessionListener"/>
    39. <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
    40. <constructor-arg value="shiro.session"/>
    41. <property name="maxAge" value="-1"/>
    42. <property name="httpOnly" value="true"/>
    43. bean>
    44. <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    45. <property name="globalSessionTimeout" value="120000"/>
    46. <property name="sessionDAO" ref="customSessionDao"/>
    47. <property name="sessionValidationInterval" value="60000"/>
    48. <property name="deleteInvalidSessions" value="true"/>
    49. <property name="sessionListeners">
    50. <list>
    51. <ref bean="shiroSessionListener"/>
    52. list>
    53. property>
    54. <property name="sessionIdCookie" ref="sessionIdCookie"/>
    55. <property name="sessionIdUrlRewritingEnabled" value="false"/>
    56. bean>
    57. beans>

    2.ehcache.xml的配置文件

    在resources中放入ehcache.xml

    1. "1.0" encoding="UTF-8"?>
    2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    4. updateCheck="false">
    5. <diskStore path="D://xxx"/>
    6. <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
    7. timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
    8. <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
    9. overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
    10. timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
    11. ehcache>

    3.授权使用缓存

    在项目中创建一个新的包ehcache,在里面创建3个类EhcacheDemo1,EhcacheUtil,EhcacheDemo2

    代码分别是EhcacheDemo1

    1. package com.hz.ssm.ehcache;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. /**
    5. * @author黄仲
    6. * @site www.Hz.com
    7. * @company 公司
    8. * @create 2022-08-29 9:58
    9. */
    10. public class EhcacheDemo1 {
    11. static Map<String,Object> cache=new HashMap<String,Object>();
    12. static Object getValue(String key){
    13. Object value=cache.get(key);
    14. if(value == null){
    15. System.out.println("hello zs");
    16. cache.put(key,new String[]{"zs"});
    17. return cache.get(key);
    18. }
    19. return value;
    20. }
    21. public static void main(String[] args) {
    22. System.out.println(getValue("sname"));
    23. System.out.println(getValue("sname"));
    24. }
    25. }

    EhcacheUtil

    1. package com.hz.ssm.ehcache;
    2. import net.sf.ehcache.Cache;
    3. import net.sf.ehcache.CacheManager;
    4. import net.sf.ehcache.Element;
    5. import java.io.InputStream;
    6. public class EhcacheUtil {
    7. private static CacheManager cacheManager;
    8. static {
    9. try {
    10. InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
    11. cacheManager = CacheManager.create(is);
    12. } catch (Exception e) {
    13. throw new RuntimeException(e);
    14. }
    15. }
    16. private EhcacheUtil() {
    17. }
    18. public static void put(String cacheName, Object key, Object value) {
    19. Cache cache = cacheManager.getCache(cacheName);
    20. if (null == cache) {
    21. //以默认配置添加一个名叫cacheName的Cache
    22. cacheManager.addCache(cacheName);
    23. cache = cacheManager.getCache(cacheName);
    24. }
    25. cache.put(new Element(key, value));
    26. }
    27. public static Object get(String cacheName, Object key) {
    28. Cache cache = cacheManager.getCache(cacheName);
    29. if (null == cache) {
    30. //以默认配置添加一个名叫cacheName的Cache
    31. cacheManager.addCache(cacheName);
    32. cache = cacheManager.getCache(cacheName);
    33. }
    34. Element element = cache.get(key);
    35. return null == element ? null : element.getValue();
    36. }
    37. public static void remove(String cacheName, Object key) {
    38. Cache cache = cacheManager.getCache(cacheName);
    39. cache.remove(key);
    40. }
    41. }

    EhcacheDemo2

    1. package com.hz.ssm.ehcache;
    2. /**
    3. * @author黄仲
    4. * @site www.Hz.com
    5. * @company 公司
    6. * @create 2022-08-29 10:20
    7. */
    8. public class EhcacheDemo2 {
    9. public static void main(String[] args) {
    10. System.out.println(System.getProperty("java.io.tmpdir"));
    11. // EhcacheUtil.put("com.javaxl.four.entity.Book", 11, "zhangsan");
    12. // System.out.println(EhcacheUtil.get("com.javaxl.four.entity.Book", 11));
    13. EhcacheUtil.put("com.javaxl.one.entity.User", 11, "zhangsan");
    14. System.out.println(EhcacheUtil.get("com.javaxl.one.entity.User", 11));
    15. }
    16. }

    要导入pom依赖

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>org.examplegroupId>
    6. <artifactId>ssm2artifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>ssm2 Maven Webappname>
    10. <url>http://www.example.comurl>
    11. <properties>
    12. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    13. <maven.compiler.source>1.8maven.compiler.source>
    14. <maven.compiler.target>1.8maven.compiler.target>
    15. <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
    16. <spring.version>5.0.2.RELEASEspring.version>
    17. <mybatis.version>3.4.5mybatis.version>
    18. <mysql.version>5.1.44mysql.version>
    19. <pagehelper.version>5.1.2pagehelper.version>
    20. <mybatis.spring.version>1.3.1mybatis.spring.version>
    21. <commons.dbcp2.version>2.1.1commons.dbcp2.version>
    22. <commons.pool2.version>2.4.3commons.pool2.version>
    23. <log4j2.version>2.9.1log4j2.version>
    24. <junit.version>4.12junit.version>
    25. <servlet.version>4.0.0servlet.version>
    26. <lombok.version>1.18.2lombok.version>
    27. <ehcache.version>2.10.0ehcache.version>
    28. <slf4j-api.version>1.7.7slf4j-api.version>
    29. properties>
    30. <dependencies>
    31. <dependency>
    32. <groupId>org.springframeworkgroupId>
    33. <artifactId>spring-contextartifactId>
    34. <version>${spring.version}version>
    35. dependency>
    36. <dependency>
    37. <groupId>org.springframeworkgroupId>
    38. <artifactId>spring-ormartifactId>
    39. <version>${spring.version}version>
    40. dependency>
    41. <dependency>
    42. <groupId>org.springframeworkgroupId>
    43. <artifactId>spring-txartifactId>
    44. <version>${spring.version}version>
    45. dependency>
    46. <dependency>
    47. <groupId>org.springframeworkgroupId>
    48. <artifactId>spring-aspectsartifactId>
    49. <version>${spring.version}version>
    50. dependency>
    51. <dependency>
    52. <groupId>org.springframeworkgroupId>
    53. <artifactId>spring-webartifactId>
    54. <version>${spring.version}version>
    55. dependency>
    56. <dependency>
    57. <groupId>org.springframeworkgroupId>
    58. <artifactId>spring-testartifactId>
    59. <version>${spring.version}version>
    60. dependency>
    61. <dependency>
    62. <groupId>org.mybatisgroupId>
    63. <artifactId>mybatisartifactId>
    64. <version>${mybatis.version}version>
    65. dependency>
    66. <dependency>
    67. <groupId>mysqlgroupId>
    68. <artifactId>mysql-connector-javaartifactId>
    69. <version>${mysql.version}version>
    70. dependency>
    71. <dependency>
    72. <groupId>com.github.pagehelpergroupId>
    73. <artifactId>pagehelperartifactId>
    74. <version>${pagehelper.version}version>
    75. dependency>
    76. <dependency>
    77. <groupId>org.mybatisgroupId>
    78. <artifactId>mybatis-springartifactId>
    79. <version>${mybatis.spring.version}version>
    80. dependency>
    81. <dependency>
    82. <groupId>org.apache.commonsgroupId>
    83. <artifactId>commons-dbcp2artifactId>
    84. <version>${commons.dbcp2.version}version>
    85. dependency>
    86. <dependency>
    87. <groupId>org.apache.commonsgroupId>
    88. <artifactId>commons-pool2artifactId>
    89. <version>${commons.pool2.version}version>
    90. dependency>
    91. <dependency>
    92. <groupId>org.apache.logging.log4jgroupId>
    93. <artifactId>log4j-coreartifactId>
    94. <version>${log4j2.version}version>
    95. dependency>
    96. <dependency>
    97. <groupId>org.apache.logging.log4jgroupId>
    98. <artifactId>log4j-apiartifactId>
    99. <version>${log4j2.version}version>
    100. dependency>
    101. <dependency>
    102. <groupId>org.apache.logging.log4jgroupId>
    103. <artifactId>log4j-webartifactId>
    104. <version>${log4j2.version}version>
    105. dependency>
    106. <dependency>
    107. <groupId>junitgroupId>
    108. <artifactId>junitartifactId>
    109. <version>${junit.version}version>
    110. <scope>testscope>
    111. dependency>
    112. <dependency>
    113. <groupId>javax.servletgroupId>
    114. <artifactId>javax.servlet-apiartifactId>
    115. <version>${servlet.version}version>
    116. <scope>providedscope>
    117. dependency>
    118. <dependency>
    119. <groupId>org.projectlombokgroupId>
    120. <artifactId>lombokartifactId>
    121. <version>${lombok.version}version>
    122. <scope>providedscope>
    123. dependency>
    124. <dependency>
    125. <groupId>org.springframeworkgroupId>
    126. <artifactId>spring-webmvcartifactId>
    127. <version>${spring.version}version>
    128. dependency>
    129. <dependency>
    130. <groupId>javax.servlet.jspgroupId>
    131. <artifactId>javax.servlet.jsp-apiartifactId>
    132. <version>2.3.3version>
    133. dependency>
    134. <dependency>
    135. <groupId>jstlgroupId>
    136. <artifactId>jstlartifactId>
    137. <version>1.2version>
    138. dependency>
    139. <dependency>
    140. <groupId>taglibsgroupId>
    141. <artifactId>standardartifactId>
    142. <version>1.1.2version>
    143. dependency>
    144. <dependency>
    145. <groupId>commons-fileuploadgroupId>
    146. <artifactId>commons-fileuploadartifactId>
    147. <version>1.3.3version>
    148. dependency>
    149. <dependency>
    150. <groupId>org.hibernategroupId>
    151. <artifactId>hibernate-validatorartifactId>
    152. <version>6.0.7.Finalversion>
    153. dependency>
    154. <dependency>
    155. <groupId>com.fasterxml.jackson.coregroupId>
    156. <artifactId>jackson-databindartifactId>
    157. <version>2.9.3version>
    158. dependency>
    159. <dependency>
    160. <groupId>com.fasterxml.jackson.coregroupId>
    161. <artifactId>jackson-coreartifactId>
    162. <version>2.9.3version>
    163. dependency>
    164. <dependency>
    165. <groupId>com.fasterxml.jackson.coregroupId>
    166. <artifactId>jackson-annotationsartifactId>
    167. <version>2.9.3version>
    168. dependency>
    169. <dependency>
    170. <groupId>org.apache.shirogroupId>
    171. <artifactId>shiro-coreartifactId>
    172. <version>1.3.2version>
    173. dependency>
    174. <dependency>
    175. <groupId>org.apache.shirogroupId>
    176. <artifactId>shiro-webartifactId>
    177. <version>1.3.2version>
    178. dependency>
    179. <dependency>
    180. <groupId>org.apache.shirogroupId>
    181. <artifactId>shiro-springartifactId>
    182. <version>1.3.2version>
    183. dependency>
    184. <dependency>
    185. <groupId>net.sf.ehcachegroupId>
    186. <artifactId>ehcacheartifactId>
    187. <version>${ehcache.version}version>
    188. dependency>
    189. <dependency>
    190. <groupId>org.slf4jgroupId>
    191. <artifactId>slf4j-apiartifactId>
    192. <version>${slf4j-api.version}version>
    193. dependency>
    194. <dependency>
    195. <groupId>org.slf4jgroupId>
    196. <artifactId>jcl-over-slf4jartifactId>
    197. <version>${slf4j-api.version}version>
    198. <scope>runtimescope>
    199. dependency>
    200. <dependency>
    201. <groupId>org.apache.logging.log4jgroupId>
    202. <artifactId>log4j-slf4j-implartifactId>
    203. <version>${log4j2.version}version>
    204. dependency>
    205. dependencies>
    206. <build>
    207. <finalName>ssm2finalName>
    208. <resources>
    209. <resource>
    210. <directory>src/main/javadirectory>
    211. <includes>
    212. <include>**/*.xmlinclude>
    213. includes>
    214. resource>
    215. <resource>
    216. <directory>src/main/resourcesdirectory>
    217. <includes>
    218. <include>jdbc.propertiesinclude>
    219. <include>*.xmlinclude>
    220. includes>
    221. resource>
    222. resources>
    223. <pluginManagement>
    224. <plugins>
    225. <plugin>
    226. <groupId>org.apache.maven.pluginsgroupId>
    227. <artifactId>maven-compiler-pluginartifactId>
    228. <version>${maven.compiler.plugin.version}version>
    229. <configuration>
    230. <source>${maven.compiler.source}source>
    231. <target>${maven.compiler.target}target>
    232. <encoding>${project.build.sourceEncoding}encoding>
    233. configuration>
    234. plugin>
    235. <plugin>
    236. <groupId>org.mybatis.generatorgroupId>
    237. <artifactId>mybatis-generator-maven-pluginartifactId>
    238. <version>1.3.2version>
    239. <dependencies>
    240. <dependency>
    241. <groupId>mysqlgroupId>
    242. <artifactId>mysql-connector-javaartifactId>
    243. <version>${mysql.version}version>
    244. dependency>
    245. dependencies>
    246. <configuration>
    247. <overwrite>trueoverwrite>
    248. configuration>
    249. plugin>
    250. <plugin>
    251. <artifactId>maven-clean-pluginartifactId>
    252. <version>3.1.0version>
    253. plugin>
    254. <plugin>
    255. <artifactId>maven-resources-pluginartifactId>
    256. <version>3.0.2version>
    257. plugin>
    258. <plugin>
    259. <artifactId>maven-compiler-pluginartifactId>
    260. <version>3.8.0version>
    261. plugin>
    262. <plugin>
    263. <artifactId>maven-surefire-pluginartifactId>
    264. <version>2.22.1version>
    265. plugin>
    266. <plugin>
    267. <artifactId>maven-war-pluginartifactId>
    268. <version>3.2.2version>
    269. plugin>
    270. <plugin>
    271. <artifactId>maven-install-pluginartifactId>
    272. <version>2.5.2version>
    273. plugin>
    274. <plugin>
    275. <artifactId>maven-deploy-pluginartifactId>
    276. <version>2.8.2version>
    277. plugin>
    278. plugins>
    279. pluginManagement>
    280. build>
    281. project>

    在ehcache中配置文件

    1. "1.0" encoding="UTF-8"?>
    2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    4. updateCheck="false">
    5. <diskStore path="D://xxx"/>
    6. <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
    7. timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
    8. <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
    9. overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
    10. timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
    11. ehcache>

    在MyRealm中改造授权方法

    1. package com.hz.ssm.shiro;
    2. import com.hz.ssm.biz.UserBiz;
    3. import com.hz.ssm.ehcache.EhcacheUtil;
    4. import com.hz.ssm.model.User;
    5. import org.apache.shiro.authc.*;
    6. import org.apache.shiro.authz.AuthorizationInfo;
    7. import org.apache.shiro.authz.SimpleAuthorizationInfo;
    8. import org.apache.shiro.realm.AuthorizingRealm;
    9. import org.apache.shiro.subject.PrincipalCollection;
    10. import org.apache.shiro.util.ByteSource;
    11. import java.util.Set;
    12. /**
    13. * @author黄仲
    14. * @site www.Hz.com
    15. * @company 公司
    16. * @create 2022-08-25 19:21
    17. */
    18. public class MyRealm extends AuthorizingRealm {
    19. public UserBiz getUserBiz() {
    20. return userBiz;
    21. }
    22. public void setUserBiz(UserBiz userBiz) {
    23. this.userBiz = userBiz;
    24. }
    25. public UserBiz userBiz;
    26. /**
    27. * 授权
    28. * @param principals
    29. * @return
    30. * 这个方法替代了shiro-web.ini
    31. * 菜单
    32. */
    33. @Override
    34. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    35. // 获取账户名
    36. String userName = principals.getPrimaryPrincipal().toString();
    37. // 先从缓存中取,缓存中没有,在查询数据库,查询出数据放入缓存
    38. String cacheName1 = "user:role:"+userName;
    39. String cacheName2 = "user:per:"+userName;
    40. // 从缓存中获取角色
    41. Set<String> role = (Set<String>) EhcacheUtil.get(cacheName1, userName);
    42. // 获取权限
    43. Set<String> per = (Set<String>) EhcacheUtil.get(cacheName2, userName);
    44. if(role == null|| role.size() ==0){
    45. // 查询对应的角色
    46. role = userBiz.getRolesByUserId(userName);
    47. System.out.println("从数据库中读取用户角色。。");
    48. EhcacheUtil.put(cacheName1,userName,role);
    49. }
    50. if(per == null|| per.size() ==0){
    51. // 查询用户对应的权限
    52. per = userBiz.getPersByUserId(userName);
    53. System.out.println("从数据库中读取用户权限。。");
    54. EhcacheUtil.put(cacheName2,userName,per);
    55. }
    56. // 拿到授权器
    57. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    58. // 将当前的登录的权限交给shiro授权器
    59. info.setStringPermissions(per);
    60. // 将当前的登录的角色交给shiro授权器
    61. info.setRoles(role);
    62. return info;
    63. }
    64. // 认正
    65. @Override
    66. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    67. String userName = token.getPrincipal().toString();
    68. User user = userBiz.queryUserByUserName(userName);
    69. AuthenticationInfo info=new SimpleAuthenticationInfo(
    70. user.getUsername(),
    71. user.getPassword(),
    72. ByteSource.Util.bytes(user.getSalt()),
    73. this.getName()
    74. );
    75. return info;
    76. }
    77. }

  • 相关阅读:
    conda安装pyhanlp遇到的问题及解决方法
    【Github】 Github访问不是私密连接问题
    【LeetCode】栈与单调栈题解汇总
    C++类作用域
    CSS & CSS3 -- 实例
    精神心理科医生:抑郁症正在好转的5种表现
    IDEA 中贼好用的插件-开发利器
    怎么突破反爬虫机制
    解决从PDF复制文字后乱码问题
    (持续更新中!)详解【计算机类&面试真题】军队文职考试 ——第一期(真题+解析)| TCP、UDP的区别;程序局部性;ICMP协议及主要功能;重定位所需的计算机硬件
  • 原文地址:https://blog.csdn.net/csnbb/article/details/126584074