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

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();
    }
}

首页访问:

posted @ 2020-04-18 20:07  努力的校长  阅读(217)  评论(0编辑  收藏  举报