springboot 实现国际化语言切换

  • Post author:
  • Post category:其他


一、配置

1、springboot配置

spring:
  messages:
    basename: i18n/messages
    encoding: UTF-8

2、文件

内容:

messages.properties和messages_zh_CN.properties

text.value=我是中国人 

messages_en_US.properties

text.value=I'm Chinese

3、代码

1、I18nConfig.java

package com.zhouzy.ssm.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.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
public class I18nConfig implements WebMvcConfigurer{
    /**
     * 默认解析器 其中locale表示默认语言
     */
    @Bean
    public LocaleResolver localeResolver() {
    	return new MyLocaleResolver();
    }
    
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        return localeChangeInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}


MyLocaleResolver.java

package com.zhouzy.ssm.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) {
      	// 从 request 域中读取传过来的参数
        String l = request.getParameter("lang");
      	// 声明 Locale 为默认语言显示
        Locale locale = Locale.getDefault();
      	// 判断传入参数是否为空
        if (!StringUtils.isEmpty(l)){
          	// 将传过来的参数,通过下划线分割,获取到地区(zh)即代码(CN)
            String[] split = l.split("_");
          	// 进行赋值
            locale = new Locale(split[0],split[1]);
        }
      	// 返回
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}


MessageUtils.java

package com.zhouzy.ssm.config;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;

public class MessageUtils extends ResourceBundleMessageSource {
    private static MessageSource messageSource;

    public static void setMessageSource(MessageSource source){
        messageSource=source;
    }
    public MessageUtils() {
        super();
        //this.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String pvsKey) {
        try {
            return messageSource.getMessage(pvsKey, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return pvsKey;
        }
    }
    /**
     * 获取单个国际化翻译值
     */
    public static String get(String pvsKey,Object ... pvParams) {
        try {
            return messageSource.getMessage(pvsKey, pvParams, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return pvsKey;
        }
    }
}

ApplicationEvent.java

package com.zhouzy.ssm.config;

import javax.annotation.Resource;

import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class ApplicationEvent implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    protected MessageSource messageSource;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        MessageUtils.setMessageSource(messageSource);
    }
}

IndexController.java

package com.zhouzy.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.zhouzy.ssm.config.MessageUtils;

/* 类注解 */
@Api(tags = "首页管理")
@Controller
public class IndexController {
	@Autowired
    private MessageSource messageSource;
	
	 /**
     * 首页
     * @author zhouzhiyao
     * @date 2021/08/03
     **/
	 @ApiOperation(value = "首页", notes = "")
	 @GetMapping("/")
     public String index(Model model,Locale locale) {
		 model.addAttribute("title", MessageUtils.get("text.value"));
         return "index";
     }
	 
}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页</title>
    <link rel="stylesheet" href="/css/layui.css">
    <script src="/layui.js" type="text/javascript"></script>
</head>
<body>
    <h2 th:text="#{text.value}">国际化</h2>
    <h2 th:text="${title}">国际化</h2>
    <a href="?lang=zh_CN">中文</a>
    <a href="?lang=en_US">英文</a>
    
</body>
</html>

二、测试



版权声明:本文为wwwzhouzy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。