1、src\main\resources\i18n
创建:lan.properties、lan_zh_CN.properties、lan_en_US.properties,默认、中文、英文。
password=密码 和 password=password
核心配置文件application.yml
server:
port: 8091
spring:
thymeleaf:
enabled: true #开启thymeleaf视图解析
encoding: utf-8 #编码
prefix: classpath:/templates/ #前缀
cache: false #是否使用缓存
mode: HTML #严格的HTML语法模式
suffix: .html #后缀名
messages:
basename: i18n.login
basename要设置成i18n.login,指定这个配置文件。
2、自定义区域解析器
package com.jay.SpringBootStudy8.config;
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 {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l = httpServletRequest.getParameter("l");
Locale locale = Locale.getDefault();
if (!("".equals(l) || l == null)) {
String[] split = l.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
3、注册区域自定义解析器 到 自定义视图解析器中
package com.jay.SpringBootStudy8.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.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
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
4、注册的区域解析器方法签名是要和WebMvcAutoConfiguration类中的一样,必须是public LocaleResolver localeResolver...
5、index.html网页
<!DOCTYPE html>
<html lang="en_US" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index</title>
</head>
<body>
<div th:text="#{login.password}"></div>
<a th:href="@{/index(l='zh_CN')}">中文</a>
<a th:href="@{/index(l='en_US')}">English</a>
</body>
</html>
6、Controller
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(Model model){
return "index";
}
}
浙公网安备 33010602011771号