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?
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");
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With