Search code examples
springwebsocketlocale

How to get locale in Spring Websocket mapping


I have methods annotated with @SubscribeMapping and @MessageMapping in a Controller and I am unable to get the current locale from inside those methods.

How can I get the locale?


Solution

  • @MessageMapping- with this annotation as method parameter you can use:

    • @Message
    • @Payload
    • @Header
    • @Headers
    • @MessageHeaders

    etc. Documentation here.

    You have at least three options, I will show you the first one:

    @MessageMapping("/url1")
    @SendTo("/url2")
    public void sendMessage(@Payload String message, @Header(name = "locale", required = false, defaultValue = "en") String locale){
       Locale locale = new Locale(locale);
       //DO SOMETHING
    }
    

    You need to remember to set this header on the client side.