首页 > 编程语言 > 详细

Springboot:员工管理之国际化(十(3))

时间:2020-04-19 00:19:12      阅读:52      评论:0      收藏:0      [点我收藏+]

1:IDEA编码设置UTF-8

技术分享图片

2:创建国际化文件

技术分享图片

i18n\login.properties  #默认语言
i18n\login_en_US.properties  #英文语言
i18n\login_zh_CN.properties  #中文语言

注:当以上三个文件创建完毕后,会自动合并成图示的结构

3:添加中英文

技术分享图片

login_en_US.properties:

login.btn=Sign in
login.password=Password
login.remember=Remember me
login.title=Please sign in
login.username=Username

login_zh_CN.properties:

login.btn=登录
login.password=密码
login.remember=记住我
login.title=请登录
login.username=用户名

4:国际化配置

spring:
  messages:
    basename: i18n.login

5:首页国际化

国际化取值:#{}

resources\templates\index.html
技术分享图片

6:首页访问(读取默认语言)

技术分享图片

7:编写中英文请求

编写index.html的中英文请求:

<a class="btn btn-sm" th:href="@{/index.html(l=‘zh_CN‘)}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l=‘en_US‘)}">English</a>

构建自定义视图解析LocaleResolver:
com\springboot\config\MyLocaleResolver.java

package com.springboot.config;

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 request) {

        String l = request.getParameter("l");//从request得到l参数

        Locale local =Locale.getDefault();//获取默认值

        if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
            local = new Locale(split[0],split[1]); //从l中获取地区和语言
        }
        return local;
    }

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

    }
}

在MyConfig类中把自定义的国际化解析器注册到spring容器中:
com\springboot\config\MyConfig.java

package com.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration //配置类注解
public class MyConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        /*访问首页视图解析器*/
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }

    //把国际化配置加入到容器中,使其生效
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

首页访问:
技术分享图片

技术分享图片

Springboot:员工管理之国际化(十(3))

原文:https://www.cnblogs.com/applesnt/p/12684605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!