Spring boot 根据浏览器实现网站资源国际化

  1. 首先在resources文件夹下创建Resources Bundle messages目录
  2. 创建messages.properties默认加载文件,内容:welcome = 欢迎使用群艺系统(default)
  3. 创建messages_en_US.properties英文资源,内容:welcome = welcome to QUNYI System(English)
  4. 创建messages_zh_CN.properties中文资源,内容:welcome = 欢迎使用群艺系统(中文)

标题在templates文件夹下创建hello.html文件

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
</head>
<body>
<p><label th:text="#{welcome}"></label></p>
</body>
</html>

标题创建国际化配置类

@Configuration
public class I18nConfig extends WebMvcConfigurerAdapter {
    @Bean
    public LocaleResolver localeResolver() {
 
        return new SessionLocaleResolver();
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

标题创建HelloController调用html模版

@Controller
@Api(value="HelloController——》》API")
@RequestMapping("/sys")
public class HelloController{

    @RequestMapping("/hello")
    public String hello(){
       Locale obj = LocaleContextHolder.getLocale();
        System.out.println("enter hello mapping------->>"+obj);
        return "/hello";
    }
}

标题我用的firefox浏览器测试的,修改区域语言:

打开firefox浏览器访问http://localhost:8090/sys/hello ,应该是看到如下信息:

欢迎使用群艺系统(中文)

那么我们修改我们的语言呢,在浏览器地址栏输入如下信息:

about:config

回车进入一个警告页面,然后点击按钮【我保证会小心】(注:由于版本不一样,可能会有些不一样,但是操作是一样的)。

在搜索框输入accept,然后找到intl.accept_languages修改对应的值,我这里原本是:

zh-cn, zh, en-us, en

为了看到效果,修改为:

en-us, en

修改完之后,刷新http://localhost:8090/sys/hello,可以看到信息:

welcome to QUNYI System(English)

转载于:https://my.oschina.net/jinhong/blog/1647718

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值