SpringBoot 之 国际化
程序员文章站
2022-07-01 12:46:49
添加国际化i18n语言配置: 模板中使用国际化语言输出及增加切换语言链接: 实现本地化解析器: 将语言解析器加入到 WebMvcConfigurer 中: ......
添加国际化i18n语言配置:
# src/main/resources/i18n/login.properties login.btn=登录
# src/main/resources/i18n/login_zh_cn.properties login.btn=登录
# src/main/resources/i18n/login_en_us.properties login.btn=sign in
模板中使用国际化语言输出及增加切换语言链接:
# src/main/resources/templates/index.html <h1 ... th:text="#{login.tip}"></h1> <input type="checkbox" value="remember-me"> [[#{login.remember}]] <button type="submit"> [[#{login.btn}]] </button> <a th:href="@{/index.html(l='zh_cn')}">中文</a> <a th:href="@{/index.html(l='en_us')}">english</a>
# src/main/resources/application.properties # 国际化文件的目录位置 spring.messages.basename=i18n
实现本地化解析器:
# src/main/java/com/wu/config/mylocaleresolver.java import org.springframework.util.stringutils; import org.springframework.web.servlet.localeresolver; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.util.locale; public class mylocaleresolver implements localeresolver { private static final string path_parameter = "l"; private static final string path_parameter_split = "_"; @override public locale resolvelocale(httpservletrequest request) { string lang = request.getparameter(path_parameter); locale locale = request.getlocale(); if (!stringutils.isempty(lang)) { string[] split = lang.split(path_parameter_split); locale = new locale(split[0], split[1]); } return locale; } @override public void setlocale(httpservletrequest request, httpservletresponse response, locale locale) { } }
将语言解析器加入到 webmvcconfigurer 中:
# src/main/java/com/wu/config/mymvcconfig.java @configuration // 标注这个类是一个配置类 public class mymvcconfig implements webmvcconfigurer { // 配置视图跳转 @override public void addviewcontrollers(viewcontrollerregistry registry) { registry.addviewcontroller("/").setviewname("index"); registry.addviewcontroller("/index.html").setviewname("index"); } // 将本地化解析器配置到容器中 @bean public localeresolver localeresolver() { return new mylocaleresolver(); } // 将视图解析器配置到容器中 @bean public viewresolver myviewresolver() { return new myviewresolver(); } // 自定义一个视图解析器 public static class myviewresolver implements viewresolver { @override public view resolveviewname(string viewname, locale locale) throws exception { return null; } } }
上一篇: 让基于CEF的应用支持自定义协议
下一篇: 百度网页快照删除服务恢复运营