1.点击链接切换国际化(给它一个参数)
<div style="margin-left: 100px;">
<a href="#" th:href="@{index.html(l='zh_CN')}">中文</a>
<a href="" th:href="@{index.html(l='en_US')}" >English</a>
</div>
2. 自定义区域解析器设置区域信息
代码:
package com.cc.springboot.component;
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;
//自定义区域解析器
public class MyLocaleResolver implements LocaleResolver {
public MyLocaleResolver() {
super();
}
// 解析区域信息
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取自定义请求头信息
String l = request.getParameter("l");
// 区域对象 默认的区域信息
Locale locale=Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
// 接收第一个参数为语言代码,国家代码
locale=new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
Ctrl+O实现接口的一些方法 Ctrl+Alt+v生成返回值
3.替换mvc自动配置类区域信息解析器(返回值和方法名是固定的,不能自定义)
package com.cc.springboot.config;
import com.cc.springboot.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MySpringMvcConfigurer {
@Bean
// 跳转首页
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("main/login");
registry.addViewController("/index.html").setViewName("main/login");
}
};
}
@Bean
// 切换语言 自己定义的区域解析器
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}