Spring Boot + thymeleaf i18n国际资源化

教程分享 > Java教程 > Thymeleaf (392) 2024-08-07 11:06:57

配置

在resources目录下面创建i18n目录,然后创建几个文件

  • messages.properties 默认显示语言内容
  • messages_en_US.properties 英语内容
  • messages_zh_CN.properties 中文内容
操作示例图-92460bb314444364ba6839a4df52aa24.png

 

messages.properties 


i18n.language.chinese=中文
i18n.language.english=English
i18n.home=首页
i18n.about=关于我们

messages_en_US.properties


i18n.language.chinese=中文
i18n.language.english=English
i18n.home=Home
i18n.about=About Us

messages_zh_CN.properties


i18n.language.chinese=中文
i18n.language.english=English
i18n.home=首页
i18n.about=关于我们

 

application.yml 配置


spring: 
  messages:
   basename: i18n/messages

注意:这里的basename 是配置的到资源文件名(不含.properties)的相对classpath路径可以配置多个,英文逗号分隔。

启动类实现WebMvcConfigurer接口


@SpringBootApplication
public class Application implements WebMvcConfigurer {
    /**
     * for i18n cookieLocale更智能
     */
    @Bean
    public LocaleResolver localeResolver(){
        return new CookieLocaleResolver();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
     
		//....其他配置.....
		
        //i18n
        LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
    }
}

Locale切换接口


@Controller
public class LocaleController {
    @GetMapping(value = "/locale")
    public String localeHandler(HttpServletRequest request) {
        String lastUrl = request.getHeader("referer");
        return "redirect:" + lastUrl;
    }
}

Locale接口调用参考


<a class="dropdown-item" th:href="@{/locale(lang=es_ES)}"
   th:text="#{i18n.language.chinese}">中文</a>
<a class="dropdown-item" th:href="@{/locale(lang=en_US)}"
   th:text="#{i18n.language.english}">English</a>

 

Locale本地化信息展示使用参考:

<li class="item active"><a href="/" th:text="#{i18n.home}">首页</a></li>
<li class="item"><a href="./about.html" th:text="#{i18n.about}">关于我们</a></li>

 

 

https://www.leftso.com/article/2407031532463557.html

相关文章
配置在resources目录下面创建i18n目录,然后创建几个文件messages.properties 默认显示语言内容messages_en_US.prop
使用thymeleaf 模板创建时间 使用thymeleaf 创建指定日期为:2023-10-18 #dates.create(2023,10,18) 使用thymeleaf ...
Thymeleaf 递归,Thymeleaf模板引擎递归展示如评论留言等场合适用
SSH/SSM项目中如何集成thymeleaf?本文将讲解SSH/SSM项目中如何集成thymeleaf模板引擎
thymeleaf 设置不校验html标签
本文说一下在thymeleaf模板引擎中,如何给 textarea 赋值
thymeleaf模板 报错信息:​​​​​​​org.thymeleaf.exceptions.TemplateInputException: Error resolving template...
环境Thymeleaf 3.0循环5次需求:输出5个li编码参考:&lt;ul&gtl; &lt;li th:each="index:${#numbers.sequence(1,
springboot 使用thymeleaf 模板引擎中url中的&引起的org.xml.sax.SAXParseException: 对实体 "uid" 的引用必须以 ';' 分隔符结尾。问题解决
设置数据源将数据写入到 Model 中 @RequestMapping("/menulist") public String MenuManagerList(M