Skip to content

Instantly share code, notes, and snippets.

create table IF NOT EXISTS languages (
id integer auto_increment,
locale varchar(2),
messagekey varchar(255),
messagecontent varchar(255),
primary key (id)
);
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
@Configuration
public class WelcomeRouter {
@Bean
public RouterFunction<ServerResponse> route(WelcomeHandler welcomeHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/index")
.and(RequestPredicates.accept(MediaType.TEXT_HTML)), welcomeHandler::hello)
.andRoute(RequestPredicates.GET("/welcome")
@Component
public class WelcomeHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse
.ok()
.contentType(MediaType.TEXT_HTML)
.render("index");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>I18N Spring Webflux</title>
</head>
<body>
<h2 data-th-text="#{label.welcome}"></h2>
<p data-th-text="#{label.content}"></p>
<p data-th-text="#{label.changeLang}"></p>
@Configuration
public class LocaleSupportConfig extends DelegatingWebFluxConfiguration {
@Override
protected LocaleContextResolver createLocaleContextResolver() {
return new RequestParamLocaleContextResolver();
}
}
public class RequestParamLocaleContextResolver implements LocaleContextResolver{
@Override
public LocaleContext resolveLocaleContext(ServerWebExchange exchange) {
Locale targetLocale = Locale.getDefault();
List<String> referLang = exchange.getRequest().getQueryParams().get("lang");
if (referLang != null && !referLang.isEmpty()) {
String lang = referLang.get(0);
targetLocale = Locale.forLanguageTag(lang);
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("languages/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
label.welcome = Welcome
label.content = This is sample project for Internalization and Localization in Webflux
label.changeLang = Supported languages
label.lang.en = English
label.lang.fr = French
label.lang.cn = Chinese
label.lang.de = German
@SpringBootApplication
public class I18NWebfluxApplication {
public static void main(String[] args) {
SpringApplication.run(I18NWebfluxApplication.class, args);
}
}