首先,展示一波实现后的界面

方案思路
-
首先知道会话什么时候超时,利用shiro中的session会话监听,每隔一段时间监听。
-
当监听会话过期时,利用WebSocket推送消息到前台提示"您长时间没有操作,请重新登录!!!"的提示框
步骤安排
- 首先创建 配置session会话监听类ShiroSessionListener(这个类后面会继续改造)
package com.ktamr.shiro.web.session;
import com.ktamr.WebSocket.WebSocketServer;
import com.ktamr.shiro.web.filter.LogoutFilter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;
/**
* 配置session监听
*/
public class ShiroSessionListener implements SessionListener {
/**
* 会话创建时触发
*
* @param session
*/
@Override
public void onStart(Session session) {
}
/**
* 退出会话时触发
*
* @param session
*/
@Override
public void onStop(Session session) {
}
/**
* 会话过期时触发
*
* @param session
*/
@Override
public void onExpiration(Session session) {
System.out.println("我过期了");
}
}
- 在权限配置加载ShiroConfig类中进行监听的配置
配置session监听的Bean
/**
* 配置session监听
*
* @return
*/
@Bean("sessionListener")
public ShiroSessionListener sessionListener() {
ShiroSessionListener sessionListener = new ShiroSessionListener();
return sessionListener;
}
在会话管理器中添加监听的配置,每10秒监听session的失效,单位为毫秒
OnlineWebSessionManager manager = new OnlineWebSessionManager();
Collection<SessionListener> listeners = new ArrayList<SessionListener>();
//配置监听
listeners.add(sessionListener());
manager.setSessionListeners(listeners);
manager.setSessionValidationInterval(10000);
- 使用WebSocket实现过期后进行推送到前端数据
首先加入maven依赖
<!--WebSocket的支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
开启WebSocket支持
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 开启WebSocket支持
*
* ServerEndpointExporter 作用
*
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer
package com.ktamr.WebSocket;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ktamr.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
*
* @ServerEndpoint 这个注解有什么作用?
*
* 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端
* 注解的值用户客户端连接访问的URL地址
*
*/
@ServerEndpoint("/imserver/{userId}")
@Component
public class WebSocketServer {
static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
/**
* 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收userId
*/
private String userId = "";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
//加入set中
} else {
webSocketMap.put(userId, this);
//加入set中
addOnlineCount();
//在线数加1
}
log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
/* try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:"+userId+",网络异常!!!!!!");
}*/
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
}
log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户消息:" + userId + ",报文:" + message);
//可以群发消息
//消息保存到数据库、redis
if (StringUtils.isNotBlank(message)) {
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId", this.userId);
String toUserId = jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
} else {
log.error("请求的userId:" + toUserId + "不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送自定义消息
*/
public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
log.info("发送消息到:" + userId + ",报文:" + message);
if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).sendMessage(message);
} else {
log.error("用户" + userId + ",不在线!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
在页面连接websocket并告诉后台,我的用户ID已经上线,大家可以对我进行发送数据
//会话过期弹出框
function admin_del(msg) {
layer.alert(msg, {
title:'系统提示'
, skin: 'layui-layer-lan'
,closeBtn: 0
}, function(index) {
layer.close(index);
location.href = "/logout";
});
}
function getSessionId(){
var c_name = 'JSESSIONID';
c_start=document.cookie.indexOf(c_name + "=");
if(c_start!=-1){
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if(c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}else{
//手动从后台传来sessionid
var JSESSIONID = $('#JSESSIONID').val();
return JSESSIONID;
}
}
//获取当前网址,如: http://localhost:8081/index
var curWwwPath = window.document.location.href;
//获取主机地址之后的目录,如: idnex
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8081
var localhostPaht = curWwwPath.substring(0, pos);
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
console.log(getSessionId());
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//ws://localhost:8082/imserver/888
var socketUrl=localhostPaht+"/imserver/"+getSessionId();
socketUrl=socketUrl.replace("https","ws").replace("http","ws");
if(socket!=null){
socket.close();
socket=null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
admin_del(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
- 进行后台发送前台数据
针对session什么时候过期的话,在第一步配置session监听(ShiroSessionListener),onExpiration会话过期时触发,在这个里面进行推送数据看,至于推送给谁,就是给sessionid的用户,我的前台也是用sessionid做用户的ID
package com.ktamr.shiro.web.session;
import com.ktamr.WebSocket.WebSocketServer;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import java.io.IOException;
/**
* 配置session监听
*/
public class ShiroSessionListener implements SessionListener {
/**
* 会话创建时触发
*
* @param session
*/
@Override
public void onStart(Session session) {
}
/**
* 退出会话时触发
*
* @param session
*/
@Override
public void onStop(Session session) {
}
/**
* 会话过期时触发
*
* @param session
*/
@Override
public void onExpiration(Session session) {
try {
WebSocketServer.sendInfo("您长时间没有操作,请重新登录!!!",session.getId().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果发现博文有问题,希望各位老鸟多多赐教
本文介绍如何使用Shiro的session监听功能与WebSocket技术结合,实现在用户会话超时时,实时推送消息到前端,提醒用户会话已过期并需重新登录。详细步骤包括配置监听器、实现WebSocketServer类、前后端交互等。
7790

被折叠的 条评论
为什么被折叠?



