前不久有个需求,需要在后台查看所有已登录的用户,系统使用的是spring mvc3.1 + spring security 3.1+ jpa 2.0 。
按官方文档中的方式去获取已登录的用户一直返加为0,经无数次折腾,终于有了可行的方案。先看下java代码部份。
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配置的关键部份
<beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />
<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>
<!-- 登录验证器 --> <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>
<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