前端页面国际化实现(SpringBoot+Thymeleaf)

一、编写配置文件

在这里插入图片描述
在resoures下创建两个以上结构相同的配置文件(例如login.properties与login_zh_CN.properties)就会自动生成ResourcesBundle。

在这里插入图片描述
点击+号,添加相应的属性与对应的值即可。
再在application.properties或application.yml里配置spring.messages.basename=i18n.login
(resources下的文件夹名和里面的文件名)

二、编写前端页面

<form class="form-signin">
	<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
	<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
	<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
	<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
	<div class="checkbox mb-3">
		<label>
  			<input type="checkbox" value="remember-me"> [[#{login.remember}]]
		</label>
	</div>
	<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
	<p class="mt-5 mb-3 text-muted">© 2019-2020</p>
	<a class="btn btn-sm" th:href="@{/index(l='zh_CN')}">中文</a>
	<a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</form>

thymeleaf语法:th:text="#{}"
#可以解析国际化配置文件的属性,在半闭合标签情况下用[[]]里面写#{}解析。

三、后端代码编写

1.编写controller类

@Controller
public class HelloController {
	//RequestMapping必须与前端点击语言时访问的路径一致
    @RequestMapping("/index")
    public String hello(){
        return "index";
    }
}

2.创建一个类实现LocaleResolver接口,并重写方法

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求中的语言参数
        String langu = request.getParameter("l");
        Locale locale=Locale.getDefault();
        //判断请求链接是否有语言参数
        if (!StringUtils.isEmpty(langu)){
            //参数形如:zh_CN,将参数进行切割
            String[] s = langu.split("_");
            //设置国家,地区
            locale=new Locale(s[0],s[1]);
        }
        return locale;
    }
}

3.向Spring容器中添加组件

@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

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

四、效果图

中文版页面英文版页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值