Spring Boot2 实战系列之语言国际化

前言

在很多网站我们可以看到可以切换语言的按钮,如果网站需要面向海外用户,那么实现网站语言国际化就显得非常必要。在 Spring Boot 中,我们可以非常方便地实现这个语言国际化的功能,下面就开始动手来实践一个可以中英切换的登录页面吧。

创建项目

项目结构图如下:


1.png

这里的登录页面使用的是 Bootstrap 官方的一个实例,下载下来,把相关静态资源文件导入到 resources 目录就好。


2.png

pom 依赖如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE
         
    
    top.yekongle
    springboot-i18n-sample
    0.0.1-SNAPSHOT
    springboot-i18n-sample
    i18n sample for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


代码编写

login.html, 登录页面,把需要进行语言替换的地方换成 thymeleaf 标签



    
        
        
        
        
        Signin Template for Bootstrap
        
        
        
        
    
 
    
        
    

在 resources 下新建一个 i18n 目录,创建 login.properties, login_en_US.properties, login_zh_CN.properties, 注意这里名字不要写错, 语言资源文件格式: 自定义标识语言代码国家地区.properties

login.properties

login.btn=登陆
login.password=密码
login.remember=记住我
login.tip=请登录
login.username=用户名

login_en_US.properties

login.btn=Sign in
login.password=Password
login.remember=remember-me
login.tip=Please sign in
login.username=UserName

login_zh_CN.properties

login.btn=登录
login.password=密码
login.remember=记住我
login.tip=请登录
login.username=用户名

编辑全局配置文件 application.properties

# 国际化i18n配置
# (包名.基础名)
spring.messages.basename=i18n.login
spring.messages.encoding=UTF-8

# Thymeleaf 配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 禁止缓存
spring.thymeleaf.cache=false

I18nLocaleResolver.java, 根据请求切换语言资源

package top.yekongle.i18n.config;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import lombok.extern.slf4j.Slf4j;

/** 
* Description: 区域解析器, 根据请求的值来返回对应的Locale
* Author: Yekongle  
*/
@Slf4j
public class I18nLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            locale = new Locale(split[0], split[1]);
        }
        log.info("Local Country: {}, language: {}", locale.getCountry(), locale.getLanguage());
        return locale;
    }

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

    }    

}

WebMvcConfig.java, 请求配置

package top.yekongle.i18n.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;

/** 
* @Description: I18n config
* @Author: Yekongle 
* @Date: Mar 22, 2020
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //设置对"/"的请求映射到login
        //如果没有逻辑业务,没有必要用控制器方法对请求进行映射  
        registry.addViewController("/").setViewName("login");
    }
 
 
    /**
     * 注册我们自定义的区域解析器,
     * 一旦将区域解析器注册到Spring容器中
     * 则SpingBoot默认提供的区域解析器将不会自动注册
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new I18nLocaleResolver();
    }
 
}

LoginController.java

package top.yekongle.i18n.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* @Author: Yekongle 
* @Date: Mar 22, 2020
*/
@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}

运行演示

项目启动后,访问 8080 端口,默认显示是中文


4.png

点击 English 可以切换到英文


3.png

项目已上传至 Github: https://github.com/yekongle/springboot-code-samples/tree/master/springboot-i18n-sample , 希望对小伙伴们有帮助哦。

你可能感兴趣的:(Spring Boot2 实战系列之语言国际化)