当前位置:
首页 >
自定义LocaleResolver实现页面中英文切换
发布时间:2025/3/20
34
豆豆
生活随笔
收集整理的这篇文章主要介绍了
自定义LocaleResolver实现页面中英文切换
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
文章目录
- 1.配置i18n(国际化)文件
- 2.页面设置值
- 3.编写自定义的LocaleResolver组件
- 4.注意点
1.配置i18n(国际化)文件
建立login和login_en_US时会自动生成Bundle
配置默认值,英文,中文
2.页面设置值
这里用了thymeleaf模板,前面的文章有提到用法
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72"><h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}" >Please sign in</h1><input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus=""><input type="password" class="form-control" th:placeholder="#{login.password}" required="" ><div class="checkbox mb-3"><label><input type="checkbox" value="remember-me" >[[#{login.remenber}]]测试一下值是否显示
两个超链接标签点击传值
3.编写自定义的LocaleResolver组件
public class MyLocalResolver implements LocaleResolver {@Overridepublic Locale resolveLocale(HttpServletRequest httpServletRequest) {//获取请求中的语言参数String language = httpServletRequest.getParameter("l");//如果没有返回值就用默认的Locale locale = Locale.getDefault();if (!StringUtils.isEmpty(language)){//zh_CN or en_USString[] split = language.split("_");//国家,地区locale = new Locale(split[0],split[1]);}return locale;}@Overridepublic void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {} }将组件配置到spring容器
@Configuration public class MyMvcConfig implements WebMvcConfigurer {@Beanpublic LocaleResolver localeResolver(){return new MyLocalResolver();} }测试
4.注意点
一定要把所有的编码都改为utf-8格式,否则可能会出现乱码
总结
以上是生活随笔为你收集整理的自定义LocaleResolver实现页面中英文切换的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Ajax+jquery实现异步验证用户名
- 下一篇: JVM面试速记