Live2D

springboot配置国际化功能

1.在resources文件夹下创建i18n文件夹

 

 会自动创建message.properties,message_en_US.properties和message_zh_CN.properties配置文件

 

2.点击Resource Bundle添加数据

 

 

 

 

 3.修改application.yml

 

 messages:   # 配置国际化绑定的文件 不绑定会乱码
    encoding: utf-8
    basename: i18n.message

4.导入thymeleaf和web启动类jar包

1         <dependency>
2             <groupId>org.springframework.boot</groupId>
3             <artifactId>spring-boot-starter-thymeleaf</artifactId>
4         </dependency>
5         <dependency>
6             <groupId>org.springframework.boot</groupId>
7             <artifactId>spring-boot-starter-web</artifactId>
8         </dependency>    

 

5.新建MyLocalResolver编写自定义的Locale区域解析器

/**
 * @ClassName: MyLocalResolver
 * @Description: 编写自定义的LocalResolver
 * SpringBoot默认的Locale解析器是根据请求头的区域信息进行解析的(浏览器语言)
 *  使用自定义的Locale解析器对url的区域信息进行解析达到点击切换区域效果
 *  一旦我们自定义的区域解析器注册到Spring容器中,则SpringBoot提供的将不自动注册
 * @Author: ZH
 * @Date 2021/10/19  11:54
 * @Version 1.0
 */
public class MyLocalResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest req) {
        // 获取l后面的参数
        String l = req.getParameter("l");
        Locale locale = Locale.getDefault();
        //没有l使用默认配置,有l使用自定义配置
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            // 第一个是语言代码  第二个是国家代码
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

 

6.注册我们自定义的区域解析器

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocalResolver();
    }

}

 

7.编写hello.html引入国际化内容

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
    <p th:text="#{message.name}">sda</p>
    <p th:text="#{message.age}">123</p>

</body>
</html>

 

 8.编写控制器返回hello.html

 @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

 

运行

 

 

 

 如果字符乱码修改File Encodings

 

posted @ 2021-10-19 14:10  NullPorintException  阅读(180)  评论(0)    收藏  举报