springboot 框架国际化 + thymeleaf

发布时间 2023-09-09 14:15:54作者: MaoShine

项目目录结构

image

  • 注意:导入thymeleaf,web的pom依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 配置各国语言的变量值,在resource目录下建立login.properties,login_en_US.properties,login_zh_CN.properties配置文件
    • 导入plugins Resource Bundle Edits可以便捷配置,如下图所示

image

  • 在application.properties 配置路径login.properties (就是将语言配置切入springboot的配置中去)
# spring的国际化配置
spring.messages.basename=i18n.login
此时就可以在index.html中访问到login.properties中的配置
  • 前端代码,记得加上thymeleaf的(不知道叫什莫)html头部解析配置
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.sub_title}">Please sign in</h1>
<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>
为了让前端可以切换语言,我们还要有地区解析器的配置,获取前端请求,更换login配置
  • 然后就是配置DIY的地区解析器localeResolver,(看上面的项目结构里)
package cn.mao.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import java.util.Locale;

public class AppLocaleResolver implements LocaleResolver {
    // 处理请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求参数
        String l = request.getParameter("l");

        Locale locale = Locale.getDefault();
        if (locale != null && StringUtils.isEmpty(l)) {
            return locale;
        }else{
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

  • 最后就是将localeResolver切入springboot配置,自定义了AppConfig,(看最最前面的项目结构)
package cn.mao.config;

import org.springframework.beans.factory.annotation.Qualifier;
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 AppConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");

    }


    @Bean
    @Qualifier("localeResolver") // 需要指定名,或者一下方法名不变,springboot底层装配固定了Bean的命名
    public LocaleResolver localeResolver(){
        return new AppLocaleResolver();
    }
}

  • 接下来,运行就可以了,自由切换语言了