How to configure i18n in Spring boot 2 + Webflux + Thymeleaf?

后端 未结 3 1829
清酒与你
清酒与你 2021-02-19 11:10

I just start a new project based on Spring boot 2 + Webflux. On upgrading version of spring boot and replace spring-boot-starter-web with spring-boot-starter-

3条回答
  •  广开言路
    2021-02-19 11:28

    With spring-boot-starter-webflux, there are

    • DelegatingWebFluxConfiguration
    • LocaleContextResolver

    For example, to use a query parameter "lang" to explicitly control the locale:

    1. Implement LocaleContextResolver, so that resolveLocaleContext() returns a SimpleLocaleContext determined by a GET parameter of "lang". I name this implementation QueryParamLocaleContextResolver. Note that the default LocaleContextResolver is an org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver.

    2. Create a @Configuration class that extends DelegatingWebFluxConfiguration. Override DelegatingWebFluxConfiguration.localeContextResolver() to return QueryParamLocaleContextResolver that we just created in step 1. Name this configuration class WebConfig.

    3. In WebConfig, override DelegatingWebFluxConfiguration.configureViewResolvers() and add the ThymeleafReactiveViewResolver bean as a view resolver. We do this because, for some reason, DelegatingWebFluxConfiguration will miss ThymeleafReactiveViewResolver after step 2.

    Also, I have to mention that, to use i18n with the reactive stack, this bean is necessary:

        @Bean
        public MessageSource messageSource() {
            final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
            messageSource.setBasenames("classpath:/messages");
            messageSource.setUseCodeAsDefaultMessage(true);
            messageSource.setDefaultEncoding("UTF-8");
            messageSource.setCacheSeconds(5);
            return messageSource;
    }
    

    After creating a natural template, some properties files, and a controller, you will see that:

    • localhost:8080/test?lang=zh gives you the Chinese version

    • localhost:8080/test?lang=en gives you the English version

    Just don't forget in , otherwise you may see some nasty display of Chinese characters.

提交回复
热议问题