Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebFlux WebSocket path variable

How can I get path variable in websocket handler with spring webflux?
I've tried this:

@Bean
public HandlerMapping webSocketMapping() {
    Map<String, WebSocketHandler> map = new HashMap<>();
    map.put("/path/{id}", session -> session.send(Mono.just(session.textMessage("123"))));
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setUrlMap(map);
    mapping.setOrder(-1);
    return mapping;
}

But session doesn't have any information about url parameters.
Is it possible?

like image 718
Slava Avatar asked Feb 27 '18 21:02

Slava


1 Answers

It requires some casting but it is possible.

private URI getConnectionUri(WebSocketSession session) {
    ReactorNettyWebSocketSession nettySession = (ReactorNettyWebSocketSession) session;
    return  nettySession.getHandshakeInfo().getUri();
  }

Once you have the URI use the Spring UriTemplate to get path variables.

// This can go in a static final 
UriTemplate template = new UriTemplate("/todos/{todoId}");
Map<String, String> parameters = template.match(uri.getPath());
String todoId = parameters.get("todoId");
like image 164
Mike Avatar answered Nov 15 '22 08:11

Mike