目录
在shiro里面新建一个类ShiroSessionListener 实现SessionListener3个方法
- package com.hz.ssm.shiro;
-
- import org.apache.shiro.session.Session;
- import org.apache.shiro.session.SessionListener;
-
- /**
- * @author黄仲
- * @site www.Hz.com
- * @company 公司
- * @create 2022-08-29 8:31
- */
- public class ShiroSessionListener implements SessionListener {
- @Override
- public void onStart(Session session) {
- System.out.println("ShiroSessionListener.onstart..."+session.getId());
- }
-
- @Override
- public void onStop(Session session) {
- System.out.println("ShiroSessionListener.onStop..."+session.getId());
- }
-
- @Override
- public void onExpiration(Session session) {
- System.out.println("ShiroSessionListener.onExpiration..."+session.getId());
- }
- }
-
然后到shiro.xml里面配置 稍微修改
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
-
-
- <bean id="shiroRealm" class="com.hz.ssm.shiro.MyRealm">
- <property name="userBiz" ref="userBiz" />
-
-
-
-
- <property name="credentialsMatcher">
- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
-
- <property name="hashAlgorithmName" value="md5"/>
-
- <property name="hashIterations" value="1024"/>
-
- <property name="storedCredentialsHexEncoded" value="true"/>
- bean>
- property>
- bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- <property name="sessionManager" ref="sessionManager">property>
- bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager" />
-
- <property name="loginUrl" value="/login"/>
-
-
-
- <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
-
- <property name="filterChainDefinitions">
- <value>
-
-
-
-
- /user/login=anon
- /user/updatePwd.jsp=authc
- /admin/*.jsp=roles[4]
- /user/teacher.jsp=perms[2]
-
- value>
- property>
- bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
-
-
-
-
-
-
- <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
- bean>
-
-
- <bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
- <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
- bean>
-
-
- <bean id="shiroSessionListener" class="com.hz.ssm.shiro.ShiroSessionListener"/>
-
-
- <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
-
- <constructor-arg value="shiro.session"/>
-
- <property name="maxAge" value="-1"/>
-
- <property name="httpOnly" value="true"/>
- bean>
-
-
- <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
-
- <property name="globalSessionTimeout" value="120000"/>
-
- <property name="sessionDAO" ref="customSessionDao"/>
-
- <property name="sessionValidationInterval" value="60000"/>
-
-
-
-
-
- <property name="deleteInvalidSessions" value="true"/>
-
- <property name="sessionListeners">
- <list>
- <ref bean="shiroSessionListener"/>
- list>
- property>
-
- <property name="sessionIdCookie" ref="sessionIdCookie"/>
-
- <property name="sessionIdUrlRewritingEnabled" value="false"/>
- bean>
-
-
-
- beans>
-
在resources中放入ehcache.xml
- "1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
- updateCheck="false">
-
-
-
- <diskStore path="D://xxx"/>
-
-
-
-
-
-
-
-
-
-
-
-
-
- <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
- timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
-
-
-
- <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
- overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
- timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
- ehcache>
在项目中创建一个新的包ehcache,在里面创建3个类EhcacheDemo1,EhcacheUtil,EhcacheDemo2
代码分别是EhcacheDemo1
- package com.hz.ssm.ehcache;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author黄仲
- * @site www.Hz.com
- * @company 公司
- * @create 2022-08-29 9:58
- */
- public class EhcacheDemo1 {
- static Map<String,Object> cache=new HashMap<String,Object>();
- static Object getValue(String key){
- Object value=cache.get(key);
- if(value == null){
- System.out.println("hello zs");
- cache.put(key,new String[]{"zs"});
- return cache.get(key);
- }
- return value;
- }
-
- public static void main(String[] args) {
- System.out.println(getValue("sname"));
- System.out.println(getValue("sname"));
- }
- }
-
EhcacheUtil
- package com.hz.ssm.ehcache;
-
- import net.sf.ehcache.Cache;
- import net.sf.ehcache.CacheManager;
- import net.sf.ehcache.Element;
-
- import java.io.InputStream;
-
- public class EhcacheUtil {
-
- private static CacheManager cacheManager;
-
- static {
- try {
- InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
- cacheManager = CacheManager.create(is);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private EhcacheUtil() {
- }
-
- public static void put(String cacheName, Object key, Object value) {
- Cache cache = cacheManager.getCache(cacheName);
- if (null == cache) {
- //以默认配置添加一个名叫cacheName的Cache
- cacheManager.addCache(cacheName);
- cache = cacheManager.getCache(cacheName);
- }
- cache.put(new Element(key, value));
- }
-
-
- public static Object get(String cacheName, Object key) {
- Cache cache = cacheManager.getCache(cacheName);
- if (null == cache) {
- //以默认配置添加一个名叫cacheName的Cache
- cacheManager.addCache(cacheName);
- cache = cacheManager.getCache(cacheName);
- }
- Element element = cache.get(key);
- return null == element ? null : element.getValue();
- }
-
- public static void remove(String cacheName, Object key) {
- Cache cache = cacheManager.getCache(cacheName);
- cache.remove(key);
- }
- }
-
EhcacheDemo2
- package com.hz.ssm.ehcache;
-
- /**
- * @author黄仲
- * @site www.Hz.com
- * @company 公司
- * @create 2022-08-29 10:20
- */
- public class EhcacheDemo2 {
- public static void main(String[] args) {
- System.out.println(System.getProperty("java.io.tmpdir"));
- // EhcacheUtil.put("com.javaxl.four.entity.Book", 11, "zhangsan");
- // System.out.println(EhcacheUtil.get("com.javaxl.four.entity.Book", 11));
-
- EhcacheUtil.put("com.javaxl.one.entity.User", 11, "zhangsan");
- System.out.println(EhcacheUtil.get("com.javaxl.one.entity.User", 11));
-
- }
-
- }
要导入pom依赖
- "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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0modelVersion>
-
- <groupId>org.examplegroupId>
- <artifactId>ssm2artifactId>
- <version>1.0-SNAPSHOTversion>
- <packaging>warpackaging>
-
- <name>ssm2 Maven Webappname>
-
- <url>http://www.example.comurl>
-
- <properties>
- <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
- <maven.compiler.source>1.8maven.compiler.source>
- <maven.compiler.target>1.8maven.compiler.target>
- <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
-
-
-
- <spring.version>5.0.2.RELEASEspring.version>
-
- <mybatis.version>3.4.5mybatis.version>
-
- <mysql.version>5.1.44mysql.version>
-
- <pagehelper.version>5.1.2pagehelper.version>
-
- <mybatis.spring.version>1.3.1mybatis.spring.version>
-
- <commons.dbcp2.version>2.1.1commons.dbcp2.version>
- <commons.pool2.version>2.4.3commons.pool2.version>
-
- <log4j2.version>2.9.1log4j2.version>
-
- <junit.version>4.12junit.version>
- <servlet.version>4.0.0servlet.version>
- <lombok.version>1.18.2lombok.version>
-
- <ehcache.version>2.10.0ehcache.version>
- <slf4j-api.version>1.7.7slf4j-api.version>
- properties>
-
- <dependencies>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-ormartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-txartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-aspectsartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-testartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>${mybatis.version}version>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>${mysql.version}version>
- dependency>
-
- <dependency>
- <groupId>com.github.pagehelpergroupId>
- <artifactId>pagehelperartifactId>
- <version>${pagehelper.version}version>
- dependency>
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>${mybatis.spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-dbcp2artifactId>
- <version>${commons.dbcp2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-pool2artifactId>
- <version>${commons.pool2.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-coreartifactId>
- <version>${log4j2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-apiartifactId>
- <version>${log4j2.version}version>
- dependency>
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-webartifactId>
- <version>${log4j2.version}version>
- dependency>
-
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>${junit.version}version>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>javax.servletgroupId>
- <artifactId>javax.servlet-apiartifactId>
- <version>${servlet.version}version>
- <scope>providedscope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>${lombok.version}version>
- <scope>providedscope>
- dependency>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webmvcartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>javax.servlet.jspgroupId>
- <artifactId>javax.servlet.jsp-apiartifactId>
- <version>2.3.3version>
- dependency>
- <dependency>
- <groupId>jstlgroupId>
- <artifactId>jstlartifactId>
- <version>1.2version>
- dependency>
- <dependency>
- <groupId>taglibsgroupId>
- <artifactId>standardartifactId>
- <version>1.1.2version>
- dependency>
- <dependency>
- <groupId>commons-fileuploadgroupId>
- <artifactId>commons-fileuploadartifactId>
- <version>1.3.3version>
- dependency>
-
- <dependency>
- <groupId>org.hibernategroupId>
- <artifactId>hibernate-validatorartifactId>
- <version>6.0.7.Finalversion>
- dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-databindartifactId>
- <version>2.9.3version>
- dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-coreartifactId>
- <version>2.9.3version>
- dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-annotationsartifactId>
- <version>2.9.3version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-coreartifactId>
- <version>1.3.2version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-webartifactId>
- <version>1.3.2version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-springartifactId>
- <version>1.3.2version>
- dependency>
-
- <dependency>
- <groupId>net.sf.ehcachegroupId>
- <artifactId>ehcacheartifactId>
- <version>${ehcache.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.slf4jgroupId>
- <artifactId>slf4j-apiartifactId>
- <version>${slf4j-api.version}version>
- dependency>
- <dependency>
- <groupId>org.slf4jgroupId>
- <artifactId>jcl-over-slf4jartifactId>
- <version>${slf4j-api.version}version>
- <scope>runtimescope>
- dependency>
-
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-slf4j-implartifactId>
- <version>${log4j2.version}version>
- dependency>
-
- dependencies>
-
-
- <build>
- <finalName>ssm2finalName>
- <resources>
-
- <resource>
- <directory>src/main/javadirectory>
- <includes>
- <include>**/*.xmlinclude>
- includes>
- resource>
-
- <resource>
- <directory>src/main/resourcesdirectory>
- <includes>
- <include>jdbc.propertiesinclude>
- <include>*.xmlinclude>
- includes>
- resource>
- resources>
-
- <pluginManagement>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-compiler-pluginartifactId>
- <version>${maven.compiler.plugin.version}version>
- <configuration>
- <source>${maven.compiler.source}source>
- <target>${maven.compiler.target}target>
- <encoding>${project.build.sourceEncoding}encoding>
- configuration>
- plugin>
- <plugin>
- <groupId>org.mybatis.generatorgroupId>
- <artifactId>mybatis-generator-maven-pluginartifactId>
- <version>1.3.2version>
- <dependencies>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>${mysql.version}version>
- dependency>
- dependencies>
- <configuration>
- <overwrite>trueoverwrite>
- configuration>
- plugin>
-
- <plugin>
- <artifactId>maven-clean-pluginartifactId>
- <version>3.1.0version>
- plugin>
-
- <plugin>
- <artifactId>maven-resources-pluginartifactId>
- <version>3.0.2version>
- plugin>
- <plugin>
- <artifactId>maven-compiler-pluginartifactId>
- <version>3.8.0version>
- plugin>
- <plugin>
- <artifactId>maven-surefire-pluginartifactId>
- <version>2.22.1version>
- plugin>
- <plugin>
- <artifactId>maven-war-pluginartifactId>
- <version>3.2.2version>
- plugin>
- <plugin>
- <artifactId>maven-install-pluginartifactId>
- <version>2.5.2version>
- plugin>
- <plugin>
- <artifactId>maven-deploy-pluginartifactId>
- <version>2.8.2version>
- plugin>
- plugins>
- pluginManagement>
- build>
- project>
在ehcache中配置文件
- "1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
- updateCheck="false">
-
-
-
- <diskStore path="D://xxx"/>
-
-
-
-
-
-
-
-
-
-
-
-
-
- <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
- timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
-
-
-
- <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
- overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
- timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
- ehcache>
在MyRealm中改造授权方法
- package com.hz.ssm.shiro;
-
- import com.hz.ssm.biz.UserBiz;
- import com.hz.ssm.ehcache.EhcacheUtil;
- import com.hz.ssm.model.User;
- 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.apache.shiro.util.ByteSource;
-
- import java.util.Set;
-
- /**
- * @author黄仲
- * @site www.Hz.com
- * @company 公司
- * @create 2022-08-25 19:21
- */
- public class MyRealm extends AuthorizingRealm {
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- public UserBiz userBiz;
-
- /**
- * 授权
- * @param principals
- * @return
- * 这个方法替代了shiro-web.ini
- * 菜单
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- // 获取账户名
- String userName = principals.getPrimaryPrincipal().toString();
- // 先从缓存中取,缓存中没有,在查询数据库,查询出数据放入缓存
- String cacheName1 = "user:role:"+userName;
- String cacheName2 = "user:per:"+userName;
- // 从缓存中获取角色
- Set<String> role = (Set<String>) EhcacheUtil.get(cacheName1, userName);
- // 获取权限
- Set<String> per = (Set<String>) EhcacheUtil.get(cacheName2, userName);
- if(role == null|| role.size() ==0){
- // 查询对应的角色
- role = userBiz.getRolesByUserId(userName);
- System.out.println("从数据库中读取用户角色。。");
- EhcacheUtil.put(cacheName1,userName,role);
- }
- if(per == null|| per.size() ==0){
- // 查询用户对应的权限
- per = userBiz.getPersByUserId(userName);
- System.out.println("从数据库中读取用户权限。。");
- EhcacheUtil.put(cacheName2,userName,per);
- }
-
-
- // 拿到授权器
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- // 将当前的登录的权限交给shiro授权器
- info.setStringPermissions(per);
- // 将当前的登录的角色交给shiro授权器
- info.setRoles(role);
- return info;
- }
-
- // 认正
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- String userName = token.getPrincipal().toString();
- User user = userBiz.queryUserByUserName(userName);
- AuthenticationInfo info=new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
-
- return info;
- }
- }