八、springboot国际化

本文详细介绍了在SpringBoot项目中实现国际化的步骤,包括使用SpringMVC和SpringBoot的不同方法,以及如何通过按钮实现语言切换。首先,需要编写国际化配置文件,并使用ResourceBundleMessageSource管理。在SpringBoot中,配置文件位于i18n文件夹下,通过创建不同语言的properties文件来设置显示内容。接着,通过application.properties配置生效,并在HTML中使用#{...}获取国际化值。最后,通过实现LocaleResolver接口创建自定义的语言切换功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用SpringMVC的步骤:

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

2、使用SpringBoot的步骤:

  1. 编写国际化配置文件,抽取页面需要显示的国际化消息
    在这里插入图片描述
    创建步骤:
    在resource文件夹下创建i18n文件夹,然后创建login_zh_CN.properties文件,创建好之后会自动变成国际化视图,出现“Resource Bundle ‘login’”,这时候可以右键“Resource Bundle ‘login’”进行创建,如下图:
    在这里插入图片描述
    然后点击“+”按钮,直接添加即可,如下图:
    在这里插入图片描述
    文件添加好了,进行添加属性对应的显示方式,如下图:
    在这里插入图片描述
    可以切换到Resource Bundle视图,然后添加在html中显示的内容,再依次添加它再不同语言中显示的值

  2. SpringBoot自动配好了管理国际化资源文件的组件


	private static final Resource[] NO_RESOURCES = {};

	@Bean
	@ConfigurationProperties(prefix = "spring.messages")
	public MessageSourceProperties messageSourceProperties() {
		return new MessageSourceProperties();
	}

	@Bean
	public MessageSource messageSource(MessageSourceProperties properties) {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		if (StringUtils.hasText(properties.getBasename())) {
			//设置国际化资源文件的基础名(去掉语言国家代码的)
			messageSource.setBasenames(StringUtils
					.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
		}
		if (properties.getEncoding() != null) {
			messageSource.setDefaultEncoding(properties.getEncoding().name());
		}
		messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
		Duration cacheDuration = properties.getCacheDuration();
		if (cacheDuration != null) {
			messageSource.setCacheMillis(cacheDuration.toMillis());
		}
		messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
		messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
		return messageSource;
	}
  1. 记得在我们的application.properties中添加配置参数,让我们的配置生效:
spring.messages.basename=i18n.login
  1. 去界面获取国际化的值使用#{…}
    login.html代码
 <div class="login layui-anim layui-anim-up">
        <div class="message" th:text="#{login.tip}">Please sign in</div>
        <div id="darkbannerwrap"></div>
        
        <form method="post" class="layui-form" >
            <input name="username" th:placeholder="#{login.username}"  type="text" lay-verify="required" class="layui-input" > [[#{login.username}]]
            <hr class="hr15">
            <input name="password" lay-verify="required" th:placeholder="#{login.password}"  type="password" class="layui-input"> [[#{login.password}]]
            <hr class="hr15">
            <input value="登录" lay-submit lay-filter="login" style="width:100%;" type="submit">
            <hr class="hr20" >
        </form>
    </div>

访问http://localhost:8080,然后就可以在切换浏览器语言的情况下,进行中英文切换了。

3、如何使用按钮进行语言切换?

3.1、在login.html中添加:

<a th:href="@{/login.html(l='zh_CN')}">中文 </a>
<a th:href="@{/login.html(l='en_US')}">English </a>

注意,我这里将访问的页面其实是;localhost:8080/login.html?l=zh_CN,这也是我们点击中文按钮以后生成的链接。在Thymeleaf的模板语法中,参数是不用“?”的,而是使用小括号,然后参数按照key=value的形式设置,注意单引号;

3.2、为了让自定义的配置生效,我们要做的就是覆盖或改变默认的配置,那么我们新建一个文件 MyLocaleResolver,用来实现 LocaleResolver 接口的作用;

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 httpServletRequest) {
        String l = httpServletRequest.getParameter("l");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

3.3、让我们的配置生效,当然就要把配置加入到SpringBoot的容器中,所以,在之前的配置文件中,加入Bean:

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //super.addViewControllers(registry);
        //浏览器发送/heMvc就可以成功访问到success界面
        registry.addViewController("/heMvc").setViewName("success");
    }

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

3.4、然后就可以访问项目,点击切换中英文了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值