概述
Shiro提供了Session的支持,主要用途是在Service层获取到Handler层的Session的信息,推荐在Handler层使用HttpSession。
简单用法
ShiroHandler.java:
@RequestMapping("/testShiroAnnotation")
public String testShiroAnnotation(HttpSession session) {
session.setAttribute("key", "123456789");
shiroService.testMethod();
return "redirect:/list.jsp";
}
这里使用的是HttpSession进行参数的设置(Controller层),下一行调用Service层的方法。
ShiroService.java:
@RequiresRoles(value = { "admin" })
public void testMethod() {
System.out.println("testMethod,time:" + new Date());
Session session = SecurityUtils.getSubject().getSession();
System.out.println(session.getAttribute("key"));
}
在Service可以直接进行Session的获取,可取得在Controller层的Session设置的参数。
SessionDao
将Session写到数据库里面。
(1)继承EnterpriseCacheSessionDAO
的一个bean,读写更新对Session序列化和反序列化,以及保存。
(2)需要配置一个sessionIdGenerator
的bean,用于SessionDao
在doCreate时,创建SessionId。
(3)第二步的sessioDao的bean需要配置给SessionManager
(4)SessionManager配置给SecurityManager
(5)Session序列化和反序列化用到ByteArrayOut(In)putStream和ObjectOut(In)putStream
,对象输入输出流,需要包装字节输入输出流。
会话验证调度器
Shiro提供了会话验证调度器,用于定期的验证会话是否已过期,如果过期将停止会话。
出于性能考虑,一般情况下都是获取会话时来验证会话是否过期并停止会话的;但是如在Web环境中,如果用户不主动退出是不知道会话是否过期的,因此需要定期的检测会话是否过期,因此需要定期的检测会话是否过期,Shiro提供了会话验证调度器SessionValidationScheduler
。
Shiro也提过了使用Quartz
会话验证调度器:QuartzSessionValidationScheduler
。