首先在打开HTML 引用Thymeleaf 模板
`
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.btn}">Please sign in</h1>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" >[[#{login.rememberMe}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn2}]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<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>
</form>
</body>
`
在Resource 里面创建文件夹 i18n
之后在里面创建login.properties以及后面的两个
login.properties里面的信息
解析器里面把网页传过来的参数l 解析,根据地区进行选择语言
package com.yhj.config;
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 MyLocalResolver implements LocaleResolver {
// 解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
// 获取请求中的语言参数
String language = request.getParameter("l");
Locale locale = Locale.getDefault();// 如果没有就使用默认的
// 如果请求的链接携带了国际化的参数
if(!StringUtils.isEmpty(language)){
// zh_CN
String[] split =language.split("_");
// 国家 地区
locale= new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
视图解析器进行样式加载
package com.yhj.config;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
//@EnableWebMvc
//如果标注了就会被springmvc全面接管
public class MymvcConfig implements WebMvcConfigurer {
// 样式加载不进来加一句话
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
// }
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//前端主页控制实现,可以加载样式
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
// 自定义的国际化组件就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}