本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
spring boot 创建 websocket 服务,最近遇到根据客户端 ip 创建黑名单的需求,但在 onOpen 或 onMessage 等方法中一般无法获取 ip。整合 chatgpt 和浏览器搜索结果,摸索出一种方式。
步骤如下:
1、创建过滤器,从 HttpRequest 对象中获取 ip,并存入 HttpSession 对象.
原理:websocket 握手时可以获取到 HttpRequest 对象,在过滤器中拿到 HttpRequest,这样就可以从里面获取到 ip 并存入 HttpSession。
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import zgmencrypt.tool.Verify;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
@javax.servlet.annotation.WebFilter(filterName = "sessionFilter", urlPatterns = "/*")
@Order(1)
@Component
public class WebFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpSession session = req.getSession();
session.setAttribute("user_ip", req.getRemoteHost());//获取ip存入session
if (this.judgeBlack(req.getRemoteHost()) == false) {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
2、创建 websocket 端点配置类用于配置自定义参数,获取第一步保存的 HttpSession,将 HttpSession 存入 HandshakeRequest 对象。
原理:HandshakeRequest 类用于保存握手消息,存到这个类里就可以到 websocket 端点的 onOpen 等方法里拿到了。
package zgmencrypt.config;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
3、配置端点时用注解引入第 2 步的配置类,然后在 onOpen 方法里先获取 HttpSession,再从 HttpSession 中获取自定义属性。
ServerEndpoint(value = "/webSocket", configurator = HttpSessionConfigurator.class)
@RestController
@Slf4j
public class WebSocketController {
@OnOpen
public void onOpen(Session session, EndpointConfig config) throws IOException {
// 获取WebSocket握手请求 并获取ip
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
String ip = (String) httpSession.getAttribute("user_ip");
}
}