ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
HandshakeInterceptor 拦截器拦截 http 协议的请求/响应,不拦截 ws 协议的请求/响应。 <br/> 拦截器使用步骤如下: **1. 实现拦截器接口** ```java public class HttpHandShakeInterceptor implements HandshakeInterceptor { /** * 在获取请求或响应之前进行拦截,获取一些请求或响应的数据 * * @param serverHttpRequest * @param serverHttpResponse * @param webSocketHandler * @param map 如果该方法通过,可以在监听器或controller层拿到这里设置的数据 * @return 返回false则拦截,返回true则通过 * @throws Exception */ @Override public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception { if (serverHttpRequest instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) serverHttpRequest; //... } if (serverHttpResponse instanceof HttpServletResponse) { HttpServletResponse response = (HttpServletResponse) serverHttpResponse; //... } return true; } /** * 在通过请求或响应之后被调用 * * @param serverHttpRequest * @param serverHttpResponse * @param webSocketHandler * @param e */ @Override public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { } } ``` **2. 配置类中添加拦截器** ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/endpoint-websocket") .setAllowedOrigins("*") //添加拦截器 .addInterceptors(new HttpHandShakeInterceptor()) .withSockJS(); } ```