1.效果
点击中文/English切换中英文
2.配置文件
application.properties
#国际化配置
spring.messages.basename=i18n.login
login.properties
login.tip=请登录
login.email=邮箱地址
login.password=密码
login.remember=记住我
login.submit=登陆
login_en_US.properties
login.tip=Please sign in
login.email=Email address
login.password=Password
login.remember=remember-me
login.submit=Sign in
login_zh_CN.properties
login.tip=请登录
login.email=邮箱地址
login.password=密码
login.remember=记住我
login.submit=登陆
3.自定义MyLocaleResolver以及配置类
MyLocaleResolver
package cn.yf.springboot_crud.component;
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 {
/**
* Resolve the current locale via the given request.
* Can return a default locale as fallback in any case.
*
* @param request the request to resolve the locale for
* @return the current locale (never {@code null})
*/
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] strings = l.split("_");
locale = new Locale(strings[0],strings[1]);
}
return locale;
}
/**
* Set the current locale to the given one.
*
* @param request the request to be used for locale modification
* @param response the response to be used for locale modification
* @param locale the new locale, or {@code null} to clear the locale
* @throws UnsupportedOperationException if the LocaleResolver
* implementation does not support dynamic changing of the locale
*/
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
MyMvcConfig
package cn.yf.springboot_crud.config;
import cn.yf.springboot_crud.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
@Configuration
public class MyMvcConfig {
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
4.index.html
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>