1.需要自己创建i18n目录,然后创建相应的properties文件,然后在添加页面中需要国际化的数据
2.添加需要的国际化配置
3.在项目中需要自动按钮切换时,需要在springboot中自定义一个组件LocaleResolver
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 MyLocalResolver implements LocaleResolver {
// 解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
// 获取请求中的语言参数链接
String langues = request.getParameter("l");
Locale locale = Locale.getDefault();
// 如果请求的链接携带了国际化的参数
if(!StringUtils.isEmpty(langues)){
String[] split = langues.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
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 MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
// 自定义的国际化放到Bean中就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}
4.在前端页面需要配置的地方进行设置,我的前端页面使用的是thymeleaf模板引擎