如何访问spring stomp websocket控制器内的主机信息。
@Controller
public class EventSessionController
{
@Autowired
ApplicationContext applicationContext;
@MessageMapping("/topic/sessionmessages}")
public SocketEvent messageHandler((StompHeaderAccessor accessor, SimpMessageHeaderAccessor headerAccessor, MySocketEvent eventMsg)
{
....// Need to access request uri / host
// I could access it from headers, but its empty
System.out.println(accessor.getHost());
}
}
我可以尝试将其注入MessageHeaderAccessor,但如何访问http请求上下文?
@Configuration
@EnableWebSocketMessageBroker
public class EventSocketServerConfig extends AbstractWebSocketMessageBrokerConfigurer
{
@Override
public void configureClientInboundChannel(ChannelRegistration registration)
{
registration.setInterceptors(new ChannelInterceptorAdapter()
{
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel)
{
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
accessor.setHost(.......how to get the http host?.......);
}
}
}
}
答案 0 :(得分:0)
如果我正确地提出了您的问题,您想要访问请求URI以从中获取一些参数。
为此,您可以使用HttpSessionIdHandshakeInterceptor,如下例所示,
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
protected final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS().setInterceptors(httpSessionIdHandshakeInterceptor());
}
public class HttpSessionIdHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
log.debug("beforeHandshake");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
// **** This is the request URI **********
URI uri = servletRequest.getURI();
}
return true;
}
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
log.debug("afterHandshake");
}
}
@Bean
public HttpSessionIdHandshakeInterceptor httpSessionIdHandshakeInterceptor() {
return new HttpSessionIdHandshakeInterceptor();
}
}