SpingBoot+Thymeleaf 实现页面国际化语言切换

                                         直接进入主题了哈


 

1)、编写国际化配置文件

a、在IDEA的resources文件夹下创建il8n,在il8n下创建login文件夹;

b、在login文件下创建login.properties、login_zh_CN.properties、login_en_US.properties;

login.properties:代表默认显示的语种,login_zh_CN.properties:切换为页面显示中文,login_en_US.properties:切换为页面显示英文。

如果要显示更多的语言的,则需要自己定义更多的properties文件

c、创建文件后选择 login_zh_CN.properties、login_en_US.properties任意一个文件,点击下方的Resource Bundle SpingBoot+Thymeleaf 实现页面国际化语言切换_第1张图片

2)、修改配置文件-引入

在application.properties中添加

spring.messages.basename=i18n.login

3)、去页面获取国际化的值;

#{}中的内容表示国际化处理



	
		
		
		
		
		Signin Template for Bootstrap
		
		
		
		
	

	
		
	

5)、重写 resolveLocale方法-自定义组件

package lhz.lx.demo.component;


import org.springframework.boot.autoconfigure.web.WebMvcProperties;
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");
        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 request, HttpServletResponse response, Locale locale) {

    }
}

6)、添加自定义组件

package lhz.lx.demo.config;

import lhz.lx.demo.component.MyLocaleResolver;
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.WebMvcConfigurerAdapter;

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

###页面效果展示:、

SpingBoot+Thymeleaf 实现页面国际化语言切换_第2张图片

SpingBoot+Thymeleaf 实现页面国际化语言切换_第3张图片

源码下载:SpringBoot+Thymeleaf实现国际化源码_thymeleaf国际化-Java代码类资源-CSDN下载

你可能感兴趣的:(SpringBoot,java,spring,vue.js)