SpringBoot 国际化初探

2023-12-26 12:32:50


国际化:多语言支持
i18n:国际化的英文单词是internationalization ,i和n之间包含了18个单词
SpringMVC国际化建立在Java国际化基础之上

准备国际化资源文件-messageSource

管理国际化资源文件

在这里插入图片描述
messages_zh_CN.properties

login.loginname=登录名:
login.password=密码
login.submit=提交
login.title=登录页面

messages_en_US.properties

login.loginname=Login name:
login.password=Password
login.submit=Submit
login.title=Login Page

messages.properties

配置

注:在 Spring 中需要配置的 MessageSource 现在不用配置了,Spring Boot 会通过org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration 自动帮我们配置一个 MessageSource 实例。
application.properties

# 国际化多语言配置
spring.messages.basename=i18n.messages
# 默认设置中文环境
spring.web.locale=zh_CN
# 锁定之后不可动态切换语言
spring.web.locale-resolver=fixed

输出国际化

localeResolver,语言区域解析器接口,该接口有下面三个常用实现类

AcceptHeaderLocaleResolver

默认语言区域解析器
读取用户浏览器请求头的Accept-Language标题值,判断用户当前选择语言
在这里插入图片描述
在这里插入图片描述
一般语言切换都是直接在页面上操作,页面如何修改请求头中的Accept-Language?
页面内部通过ajax修改接口请求头
这种方式明显比较麻烦,可以用下面两种方式

SessionLocaleResolver | CookieLocaleResolver

非默认,需要进行显示配置
从HrrpSession / Cookie作用域中获取所设置的语言区域
接口参数传递语言类型,spring中增加拦截器获取,然后设置到session / cookie

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    // 切换语言URL?language=zh_CN,切换后将信息存入session/cookie
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor(){
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("language");
        return lci;
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(localeChangeInterceptor());
    }
    @Bean
    public LocaleResolver localeResolver(){
        //return new CookieLocaleResolver();
        return new SessionLocaleResolver();
    }
}

配置页面-thymeleaf

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<link rel="icon" type="image/x-icon" th:href="@{/static/favicon.ico}">
<head>
    <title th:text="#{login.title}"></title>
</head>
<body>
<!--多语言切换-->
<a href="loginForm?language=zh_CN">中文</a><a href="loginForm?language=en_US">英文</a>
<form action="/login">
    <table>
        <tr>
            <td th:text="#{login.loginname}"></td>
            <td><input type="text" name="loginname"/></td>
        </tr>
        <tr>
            <td th:text="#{login.password}"></td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr>
            <td><input type="submit" th:value="#{login.submit}"/></td>
        </tr>
    </table>
</form>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

文章来源:https://blog.csdn.net/weixin_40970987/article/details/135197631
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。