Spring Boot页面国际化

GitHub:SpringBootDemo
Gitee:SpringBootDemo
微信公众号:在这里插入图片描述

0 开发环境

  • JDK:1.8
  • Spring Boot:2.7.18

1 检查配置

确保File -> Settings… -> Editor -> File Encodings 配置中编码为UTF-8,否则后续会出现乱码

在这里插入图片描述

2 安装插件

安装Resource Bundle Editor插件后,Resource Bundle就可以可视化编程了

在这里插入图片描述

3 新建配置文件

3.1 resources下新建i18n目录

其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数,是“国际化”的简称

3.2 i18n下新建配置文件

新建login.properties国际化默认配置文件,再新建login_zh_CN.properties中文配置文件,此时,系统会自动识别到国际化配置,将文件合并目录并切换到国际化视图。

在这里插入图片描述

我们就可以直接在 Resource Bundle ‘login’ 文件夹上右键添加其他语言配置文件

在这里插入图片描述

比如添加英语配置文件

在这里插入图片描述

3.3 编写配置文件

打开其中一个配置文件,切换到Resource Bundle视图,点击 +,即可添加配置

在这里插入图片描述

比如添加login.username配置,添加完成后,页面上会出现3个录入框,可配置不同语言的值

在这里插入图片描述

配置完成后,所有配置文件都会自动配置上对应值,比如

在这里插入图片描述

完整配置如下

login.btn=登录
login.error=用户名或密码错误
login.password=密码
login.username=用户名

4 配置yml

spring:
  messages:
    basename: i18n.login

5 页面国际化

5.1 引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

5.2 新建登录页

resources目录下新建templates目录,再新建login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>

    <style>
        .container {
            width: 300px;
            margin: auto;
            padding: 40px;
            border: 1px solid #ccc;
            background-color: white;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            margin-bottom: 10px;
        }

        input {
            width: 100%;
            padding: 6px;
            border: 1px solid #ccc;
            outline: none;
        }

        button {
            width: 100%;
            padding: 10px;
            color: white;
            background-color: #4CAF50;
            cursor: pointer;
            border: none;
            outline: none;
        }

        .language {
            width: 100%;
            text-align: center;
            margin-top: 10px;
        }

        .language a {
            color: blue;
            cursor: pointer;
            padding: 10px;
        }

        button:hover,
        a:hover {
            opacity: 0.9;
        }
    </style>
</head>
<body>
<div class="container">
    <form action="" method="post">
        <label for="username" th:text="#{login.username}"></label>
        <input type="text" id="username" name="username"><br><br>

        <label for="password" th:text="#{login.password}"></label>
        <input type="password" id="password" name="password"><br><br>

        <button type="submit" th:text="#{login.btn}"></button>
    </form>
</div>
<div class="language">
    <a th:href="@{/login.html(l=zh_CN)}">中文</a>
    <a th:href="@{/login.html(l=en_US)}">English</a>
</div>
</body>
</html>

5.3 新建Controller

@Controller
public class LoginController {

    @GetMapping(value = "login.html")
    public String login() {
        return "login";
    }
}

5.4 新建配置类

页面能够实现国际化,是通过Locale区域信息对象来实现的。

WebMvcAutoConfiguration中配置了默认的localeResolver,我们自定义一个LocaleResolver并注入容器,来替换默认的localeResolver。

注意:注入的bean名称必须为localeResolver,因为**@ConditionalOnMissingBean**会判断是否已经注入了bean

在这里插入图片描述

@Configuration
public class GlobalLocaleResolver implements LocaleResolver {

    /**
     * 解析请求
     *
     * @param request
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //默认地区
        Locale locale = request.getLocale();

        //获取请求中的语言参数
        String language = request.getParameter("l");
        if (!StringUtils.isEmpty(language)) {
            //zh_CN 国家_地区
            String[] values = language.split("_");
            locale = new Locale(values[0], values[1]);
        }

        return locale;
    }

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

    }

    @Bean
    public LocaleResolver localeResolver() {
        return new GlobalLocaleResolver();
    }
}

5.5 测试

启动服务,浏览器访问127.0.0.1:8090/login.html

在这里插入图片描述

切换英语:

在这里插入图片描述

切换中文:

在这里插入图片描述

页面可正常切换中英文,测试通过。

7 返回信息国际化

7.1 新建工具类

public class I18nUtils {

    public static String getMessage(String key) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/login");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource.getMessage(key, null, locale);
    }
}

7.2 新建Service

@Service
public class UserService {

    public String login() {
        return I18nUtils.getMessage("login.error");
    }
}

7.3 新建Controller

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "login")
    public String login() {
        return userService.login();
    }
}

7.4 测试

启动服务,Postman请求,默认中文如下:

在这里插入图片描述

附:HTTP请求头Accept-Language含义

Accept-Language:zh-CN,zh;q=0.9

Accept-Language:浏览器支持的语言类型

zh-CN:简体中文

zh:中国地区

q:用户对该范围指定的语言的偏好,为空则默认为1,范围[0, 1],值越大,权重越大

英语如下:

在这里插入图片描述

根据传入的地区信息,返回对应语言的提示信息,测试通过。

8 返回信息拼接参数

上面我们正常返回了中英文的用户名或密码错误,现在升级一下,返回类似 xxx用户名或密码错误

8.1 调整配置文件

在这里插入图片描述

8.2 调整工具类

public class I18nUtils {

    public static String getMessage(String key) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/login");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource.getMessage(key, null, locale);
    }

    public static String getMessage(String key, Object... args) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/login");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource.getMessage(key, args, locale);
    }
}

8.3 调整Service

@Service
public class UserService {

    public String login() {
        return I18nUtils.getMessage("login.error");
    }

    public String loginSuccess(String username) {
        return I18nUtils.getMessage("login.success", username, new Date());
    }
}

8.4 调整Controller

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "login")
    public String login() {
        return userService.login();
    }

    @PostMapping(value = "loginSuccess")
    public String loginSuccess(@RequestParam("username") String username) {
        return userService.loginSuccess(username);
    }
}

8.5 测试

启动服务,Postman请求,中文如下:

在这里插入图片描述

英语如下:

在这里插入图片描述

根据传入的地区信息,返回对应语言的提示信息,且正确组装传入的参数,测试通过。

至此,国际化完成,且测试通过。

  • 16
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 提供了很好的国际化支持,您可以采用以下步骤: 1. 在 resources 目录下创建一个 messages 文件夹,然后创建 messages.properties 和 messages_en.properties 文件。其中 messages.properties 文件为默认的无法匹配的任何语言环境的文件。messages_en.properties 为英语环境下的文件。 2. 在 properties 文件中增加需要国际化翻译的字符串,例如: ```properties greeting=欢迎, Welcome! ``` 3. 在代码中使用 @Value 注解来获取字符串,在字符串中使用 { } 来引用对应的 properties 文件中的字符串。例如: ```java @Value("${greeting}") private String greeting; ``` 4. 在代码中使用 LocaleResolver 将使用的 Locale 信息设置到 Request 上下文中,例如: ```java @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(Locale.US); //默认为英语 return localeResolver; } ``` 5. 在 Controller 层的方法中返回 ModelAndView 时增加语言参数,例如: ```java @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView index(HttpServletRequest request) { Locale locale = localeResolver.resolveLocale(request); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("greeting", greeting); return modelAndView; } ``` 6. 在 html 页面中使用 thymeleaf 的 i18n 标签来获取字符串,例如: ```html <h1 th:text="#{greeting}"></h1> ``` 这样就可以实现 Spring Boot 项目的国际化了,支持多种语言,前提是在 messages 文件夹下新增对应语言的 messages 文件即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值