美文网首页
Spring Boot2 实战系列之语言国际化

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

作者: _星辰夜风 | 来源:发表于2020-05-16 18:06 被阅读0次

    前言

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

    创建项目

    项目结构图如下:


    1.png

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


    2.png

    pom 依赖如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.5.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>top.yekongle</groupId>
        <artifactId>springboot-i18n-sample</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboot-i18n-sample</name>
        <description>i18n sample for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    代码编写

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

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <meta name="description" content="">
            <meta name="author" content="">
            <title>Signin Template for Bootstrap</title>
            <!-- Bootstrap core CSS -->
            <link href="asserts/css/bootstrap.min.css" rel="stylesheet">
            <!-- Custom styles for this template -->
            <link href="asserts/css/signin.css" rel="stylesheet">
        </head>
     
        <body class="text-center">
            <form class="form-signin" action="dashboard.html">
                <img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
                <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
                <label class="sr-only">Username</label>
                <input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
                <label class="sr-only">Password</label>
                <input type="password" class="form-control" th:placeholder="#{login.password}" required="">
                <div class="checkbox mb-3">
                    <label>
              <input type="checkbox" value="remember">  [[#{login.remember}]]
            </label>
                </div>
                <button class="btn btn-lg btn-primary btn-block" th:text="#{login.btn}" type="submit">Sign in</button>
                <p class="mt-5 mb-3 text-muted">© 2017-2020</p>
                <a class="btn btn-sm" th:href="@{/login(l='zh_CN')}">中文</a>
                <a class="btn btn-sm" th:href="@{/login(l='en_US')}">English</a>
            </form>
        </body>
    </html>
    

    在 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 实战系列之语言国际化

          本文链接:https://www.haomeiwen.com/subject/uayrohtx.html