SpringBoot学习笔记(五)SpringBoot进行Web开发-多语支持国际化

多语国际化在SpringMVC中的使用

  1. 编写国际化配置文件。
  2. 使用ResourceBundleMessageSource管理国际化资源文件。
  3. 在JSP页面中可以使用 fmt:message 取出国际化的内容。

SpringBoot中的多语国际化

  1. 编写国际化配置文件,抽取页面需要显示的国际化消息
  2. SpringBoot自動配置好了管理國際化資源的組件

国际化原理

  1. local区域信息对象
  2. LocalResolver获取区域信息对象
  3. 这是SpringBoot中自动配置默认的区域信息解析器。根据前端请求头中的 Accept-Language: 来响应国际化
    在这里插入图片描述

示例:

  1. 编写国际化语言参照配置文件
    在这里插入图片描述
  2. application.properties 中写上 spring.messages.basename=i18n.genner
  3. 测试运行,当更改浏览器默认语言时,页面的语言会跟随其修改
  4. 问题:我需要根据我的前端页面按钮来让用户修改语言
  5. 编写前端页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
    <link rel="icon" href="favicon.ico">
</head>
<body>
    <h1>TEMPLATES HELLO WORLD</h1>
    <h1 th:text="#{genner.hello}"></h1>
    <h1 th:text="#{genner.welcome}"></h1>

    <a th:href="@{index.html(l='zh_CN')}" th:text="#{genner.language.simple}">中文简体</a>
    <a th:href="@{index.html(l='zh_Tr')}"  th:text="#{genner.language.tradition}">中文繁体</a>
    <a th:href="@{index.html(l='en_US')}"  th:text="#{genner.language.english}">英文</a>
</body>
<script src="/jquery.js" th:src="@{/webjars/jquery.3.5.1/jquery.js}"></script>
</html>
  1. 编写区域信息解析器
package com.hx.component;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 国际化:我们可以在连接中携带上区域信息
 */
public class MylocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String[] temp = l.split("_");
            String language = temp[0];
            String country = temp[1];
            locale = new Locale(language,country);
        }
        return locale;
    }

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

    }
}
  1. 编写MyMvcConfig将MylocaleResolver交给容器管理
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        //浏览器发送/hx请求,请求到hi.html页面
        registry.addViewController("/hx").setViewName("hi");
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

    @Bean
    public LocaleResolver localeResolver(){
        return new MylocaleResolver();
    }
}
posted @   Huathy  阅读(34)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
点击右上角即可分享
微信分享提示