6

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?

Slava
  • 311
  • 3
  • 9

1 Answers1

2

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");
Mike
  • 164
  • 1
  • 4