Shiro-Session

  • 概述

  Shiro提供了完整的企業級會話管理功能,不依賴於底層容器(如web容器tomcat),無論JavaSE仍是JavaEE環境均可以使用,提供了會話管理、會話事件監聽、會話存儲/持久化、容器無關的集羣、失效/過時支持、對Web 的透明支持、SSO 單點登陸的支持等特性。java

 

  • 會話相關的API

  

  

 

  • 會話監聽器

  會話監聽器用於監聽會話建立、過時及中止事件web

  

 

   添加Session,這裏添加的時候使用的是 HttpSession數據庫

@RequestMapping("/shiroMethod")
    public String shiroServiceMethod(HttpSession session){
        session.setAttribute("key", "value12345");
        
        shiroService.shiroServiceMethod();
        return "redirect:/list.jsp";
    }

 

   在Service層中獲取Session,注意這裏使用的是Shiro提供的Sessionapache

  

package com.java.shiro.services;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;

public class ShiroService {

    @RequiresRoles({ "admin" })
    public void shiroServiceMethod() {

        Session session = SecurityUtils.getSubject().getSession();
        System.out.println("session: " + session.getAttribute("key"));

        System.out.println("Test ShiroServiceMethod, time: " + new Date());
    }

}

 

 

 這樣的好處是,即使是在Service層也能訪問到Session的數據,開發的時候是很方便的,這是Shiro提供的Session一個很重要的應用緩存

 

SessionDaotomcat

  能夠把Session存到數據庫中,對session進行增刪改查操做。session

 

在開發中推薦 繼承 EnterpreiseCacheSessionDAOapp

 

  思路:jsp

  

 

  配置示例:性能

  

 

  

 

咱們把配置好的sessionManager 做爲SecurityManager的屬性進行配置。

  數據表:

create table sessions (
id varchar(200),
session varchar(2000),
constraint pk_sessionsprimary key(id)
) charset=utf8 ENGINE=InnoDB;

 

   Session Dao

  

  

  在進行Session操做時,咱們須要將這個Session對象進行序列化的操做

  SerializableUtils

  

  配置完成。

   會話驗證調度器

  

 

  實際上會在底層開一個線程,驗證會話是否過時了,使用會話驗證會影響性能,開發是用的很少。

 

緩存

  CacheManagerAware接口

  Shiro內部相應的組件(DefaultSecurityManager) 會自動檢測相應的對象(如Realm) 是否實現了CacheManagerAware並自動注入相應的CacheManager。

  Realm緩存

  Shiro 提供了 CachingRealm,其實實現了CacheManagerAware 接口,提供了緩存的一些基礎實現;

  AuthenticatingRealm 及 AuthorizingRealm也分別提供了對 AuthenticationInfo 和  AuthorizationInfo信息的緩存。

  Session緩存

  

相關文章
相關標籤/搜索