1.先在application.properties里声明国际化文件夹位置
spring.thymeleaf.cache=false spring.messages.basename=i18n.login
2.定义文件类
package com.example.mvc01.config; import org.springframework.web.servlet.LocaleResolver; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * @author 兵兵有你 * @date 2021/10/31 0031 15:04 * @Email 1360968945@qq.com */ public class MylocalResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { String language = request.getParameter("l"); Locale locale = Locale.getDefault(); if(!StringUtils.isEmpty(language)){ String[] split = language.split("_"); locale = new Locale(split[0],split[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { } }
3.注入bean中
@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 MylocalResolver(); } }
4.resources/i18n/目录下定义好文件如下和文件内容
login.properties --内容如lgin.tip=登陆
login_en_US.properties
login_zh_CN.properties
5.修改html文件里的模板
//语言切换链接 <h1 class="h4 text-gray-900 mb-4"> <a th:href="@{/index.html(l='zh_CN')}">中文 </a> <a th:href="@{/index.html(l='en_US')}"> English</a> </h1> //文字显示内容用#号 <a href="index.html" class="btn btn-primary btn-user btn-block" :th th:text="#{login.login}">
最好点击不同的语言,上面的登陆按钮就会根据properties里的内容显示