springboot国际化

springboot国际化

a.在resources下新建文件夹il8n

b.在il8n文件夹下新建国际化的配置文件:即在不同语言的情况下对应不同的提示,包括 默认:login.properties 英文:login_en_US.properties 中文:login_zh_CN.properties 将页面中需要格式化的文字进行设置:如:提示请登录,用户名,密码,记住,登录按钮

c.讲html页面中的对应的标签通过thymeleaf进行替换 #{}

  文本:提示请登录:th:text="#{login.tip}"
     输入框提示:th:placeholder="#{login.username}"   th:placeholder="#{login.username}"
     记住单选框:在标签外: [[#{login.remember}]]
     登录按钮的提示: th:text="#{login.btn}"

d.乱码解决:

局部(改项目中)的配置文件编码设置: setting-->file Encoding:设置properties files:UTF-8,勾选单选框 全局的设置: 以上的国际化已设置成功,根据浏览器默认的语言

接下来根据中英文按钮切换语言 1.在连接上携带区域信息

 <a class="btn btn-sm" th:href="@{/atguigu(l='zh_CN')}">中文</a>
 <a class="btn btn-sm" th:href="@{/atguigu(l='en_US')}">English</a>
 注意:atgugu是自定义访问index.html的访问路径
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);
         //通过访问atguigu进入index页面
         registry.addViewController("atguigu").setViewName("index");
     }
 }
 ​
 ​

 

2.编写区域信息解析器:新建component.MyLocalResolver类

 
package com.atguigu.crud.component;
 import org.springframework.web.servlet.LocaleResolver;
 import org.thymeleaf.util.StringUtils;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.util.Locale;
 /**
  * 在链接上携带区域信息
  */
 public class MyLocalResolver implements LocaleResolver {
     @Override
     public Locale resolveLocale(HttpServletRequest request) {
         //获取参数l的值
         String l = request.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.将区域信息解析器添加在组件中:在com/atguigu/crud/config/MyMvcConfig.java中
 @Bean
 public LocaleResolver localeResolver(){
     return new MyLocalResolver();
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值