springboot 实现国际化语言切换

一、配置

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>

二、测试

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wwwzhouzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值