spring security 3.1获取所有已登录用户的终极方案 - bewithme - ITeye博客

spring security 3.1获取所有已登录用户的终极方案

博客分类:* 技巧

阅读更多

      前不久有个需求,需要在后台查看所有已登录的用户,系统使用的是spring mvc3.1 + spring security 3.1+ jpa 2.0 。

     按官方文档中的方式去获取已登录的用户一直返加为0,经无数次折腾,终于有了可行的方案。先看下java代码部份。

Java代码  收藏代码 "收藏这段代码")

  1. public String queryLoginUser(int start,int limit){  
  2.         List<Object> slist =sessionRegistry.getAllPrincipals();  
  3.         int totalCount=slist.size();  
  4.         if(slist.size()==0){  
  5.                return"{totalCount:" + totalCount + ",data:[]}";  
  6.         }  
  7.         SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  8.         List<Object> pageList=slist.subList(start,limit>slist.size()?slist.size():limit);  
  9.         StringBuffer retVal=new StringBuffer("[");  
  10.         int k=0;  
  11.         for(int i=0;i<pageList.size();i++){  
  12.             List<SessionInformation> sessionList = sessionRegistry.getAllSessions(pageList.get(i),true);   
  13.             User user=(User)pageList.get(i);  
  14.             for(SessionInformation t:sessionList){  
  15.                 if(k!=0){  
  16.                     retVal.append(",");  
  17.                 }  
  18.                 retVal.append("{\"id\":\""+k+"\",\"userName\":\""+user.getUsername()+"\",\"sessionId\":\""+t.getSessionId()+"\",\"lastRequest\":\""+sdf.format(t.getLastRequest())+"\"}");  
  19.                 k=k+1;  
  20.             }  
  21.         }  
  22.         retVal.append("]");  
  23.         return"{totalCount:" + totalCount + ",data:"+ retVal.toString() + "}";  
  24.     }  

public String queryLoginUser(int start,int limit){

    List<Object> slist =sessionRegistry.getAllPrincipals();
    int totalCount=slist.size();
    if(slist.size()==0){
           return "{totalCount:" + totalCount + ",data:\[\]}";
    }
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    List<Object> pageList=slist.subList(start,limit>slist.size()?slist.size():limit);
    StringBuffer retVal=new StringBuffer("\[");
    int k=0;
    for(int i=0;i<pageList.size();i++){
        List<SessionInformation> sessionList = sessionRegistry.getAllSessions(pageList.get(i),true); 
        User user=(User)pageList.get(i);
        for(SessionInformation t:sessionList){
            if(k!=0){
                retVal.append(",");
            }
            retVal.append("{\\"id\\":\\""+k+"\\",\\"userName\\":\\""+user.getUsername()+"\\",\\"sessionId\\":\\""+t.getSessionId()+"\\",\\"lastRequest\\":\\""+sdf.format(t.getLastRequest())+"\\"}");
            k=k+1;
        }
    }
    retVal.append("\]");
    return "{totalCount:" + totalCount + ",data:"+ retVal.toString() + "}";
}

 该方法实现了对当前登录用户的分页查询,并返回Json数据格式。

   以下是xml配置的关键部份

Java代码  收藏代码 "收藏这段代码")

  1. <beans:bean id="sessionRegistry"class="org.springframework.security.core.session.SessionRegistryImpl" />  

    <beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

Java代码  收藏代码 "收藏这段代码")

  1. <beans:bean id="sas"class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">  
  2.   <beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />  
  3.   <beans:property name="maximumSessions" value="1" />  
  4.   <beans:property name="exceptionIfMaximumExceeded" value="true" />  
  5.  </beans:bean>  

<beans:bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
<beans:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<beans:property name="maximumSessions" value="1" />
<beans:property name="exceptionIfMaximumExceeded" value="true" />
</beans:bean>

Java代码  收藏代码 "收藏这段代码")

  1.    <!-- 登录验证器 -->  
  2.    <beans:bean id="loginFilter"class="com.verysoft.baseframework.security.MyUsernamePasswordAuthenticationFilter">  
  3.     <beans:property name="sessionAuthenticationStrategy" ref="sas"/><!--此配置可实现获取所有登录用户信息 -->  
  4.     <beans:property name="filterProcessesUrl" value="/j_spring_security_check"></beans:property>  
  5.     <beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"></beans:property>  
  6.     <beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"></beans:property>  
  7.     <beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>  
  8.     <beans:property name="userDao" ref="userDao"></beans:property>  
  9. </beans:bean>  

    <!-- 登录验证器 -->
    <beans:bean id="loginFilter" class="com.verysoft.baseframework.security.MyUsernamePasswordAuthenticationFilter">

       <beans:property name="sessionAuthenticationStrategy" ref="sas"/><!--此配置可实现获取所有登录用户信息 -->
       <beans:property name="filterProcessesUrl" value="/j\_spring\_security_check"></beans:property>
       <beans:property name="authenticationSuccessHandler" ref="loginLogAuthenticationSuccessHandler"></beans:property>
       <beans:property name="authenticationFailureHandler" ref="simpleUrlAuthenticationFailureHandler"></beans:property>
       <beans:property name="authenticationManager" ref="myAuthenticationManager"></beans:property>
       <beans:property name="userDao" ref="userDao"></beans:property>

    </beans:bean>

Java代码  收藏代码 "收藏这段代码")

  1. <http use-expressions="true"  entry-point-ref="authenticationProcessingFilterEntryPoint">  
  2.       <logout delete-cookies="JSESSIONID"  invalidate-session="true" />  
  3.       <!-- 实现免登陆验证  
  4.       <remember-me /> -->  
  5.       <!-- <custom-filter  ref="concurrencyFilter" position="CONCURRENT_SESSION_FILTER"  />  -->  
  6.         <custom-filter ref="loginFilter" position="FORM_LOGIN_FILTER"  />  
  7. <custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR"/>  
  8. <session-management session-fixation-protection="none"  />  
  9.   </http>  

    <http use-expressions="true" entry-point-ref="authenticationProcessingFilterEntryPoint">

      <logout delete-cookies="JSESSIONID"  invalidate-session="true" />
      <!\-\- 实现免登陆验证
      <remember-me /> -->
      <!\-\- <custom-filter  ref="concurrencyFilter" position="CONCURRENT\_SESSION\_FILTER"  />  -->
         <custom-filter ref="loginFilter" position="FORM\_LOGIN\_FILTER"  />
      <custom-filter ref="securityFilter" before="FILTER\_SECURITY\_INTERCEPTOR"/>
      <session-management session-fixation-protection="none"  />

    </http>

此方案经本人验证通过,配置文件在附件中,有其它问题可联系本人QQ:359709421

全部代码在云盘  http://yunpan.cn/csQyg47f3gBkX (提取码:35a9)

 我的网店,有劳各位参观参观  http://mrs-x.taobao.com/

[

资深Java项目团队历时1年打造,实战精髓大揭秘!

Java系统学习全案:五大阶段学习系统规划、8大企业级项目贯穿全程。限时2折秒杀。立省4688元!

](http://www.baidu.com/cb.php?c=IgF_pyfqnHmkPjbvrHT0IZ0qnfK9ujYzrH6YrjmY0Aw-5Hnsn16YnjT0TAq15HfLP1fkrHn0T1YvrjD3P17bPhnYrjR4Pvc40AwY5HDdPWD1PjbYPHf0IgF_5y9YIZK1rBtEuywdQhP1uA38UhNYQLwETA-WQvG9IhDk5LNYUNq1ULNzmvRqmhkEuv-Yug--0ZFb5HDk0AFV5HD0TZcqn0KdpyfqnHRLPjnvnfKEpyfqnHc4rj6kP0KWpyfqP1n4PHn10AqLUWYs0ZK45HcsP6KWThnqPjbYPHn)

分享到:

java 获取windows系统安装的证书或证书链 | js获取URL中的请求参数

评论

3 楼 不知谁唱唱给谁 2015-11-27   引用

楼主是好人 还给了我源码,非常感谢  http://yunpan.cn/csQyg47f3gBkX (提取码:35a9) 

2 楼 a958048434 2015-02-27   引用

代码部分太少了

1 楼 a958048434 2015-02-26   引用

楼主能不能把文件完整发过来啊,本人刚接触security,就遇到一个难题

发表评论
表情图标

字体颜色: 标准深红红色橙色棕色黄色绿色橄榄青色蓝色深蓝靛蓝紫色灰色白色黑色 字体大小: 标准1 (xx-small)2 (x-small)3 (small)4 (medium)5 (large)6 (x-large)7 (xx-large) 对齐: 标准居左居中居右

提示:选择您需要装饰的文字, 按上列按钮即可添加上相应的标签

(快捷键 Alt+S / Ctrl+Enter)

相关资源推荐

上滑加载更多


Original url: Access
Created at: 2019-06-24 12:12:09
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论