The WebSocketConfigurer interface is used to map the handler with its specific URL in the registerWebSocketHandlers() method, as shown in the following code:
@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(createHandler(), "/webSocketHandler"); } @Bean public WebSocketHandler createMyHandler() { return new MyWebSocketHandler(); } }
Here, our WebSocketHandler interface is mapped to the /webSocketHandler URL.
The customization of WebSocketHandler for the handshake can be done as follows:
@Configuration @EnableWebSocket public class MyWebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry
registry) { registry.addHandler(createHandler(), "/webSocketHandler").addInterceptors (new HttpSessionHandshakeInterceptor()); } @Bean public WebSocketHandler createMyHandler() { return new MyWebSocketHandler(); } }
The HandshakeInterceptor interface exposes the beforeHandshake() and afterhandshake() methods to customize the WebSocket handshake. The HttpSessionHandshakeInterceptor method facilitates binding information from the HTTP session to the handshake attributes under the name HTTP_SESSION_ID_ATTR_NAME. These attributes can be used as the WebSocketSession.getAttributes() method.