美文网首页
SpringBoot配置资源国际化

SpringBoot配置资源国际化

作者: 皮多堡 | 来源:发表于2018-08-07 14:12 被阅读0次

1.在resources目录下添加三个国际化配置文件

  • messages.properties
message = 欢迎使用国际化(默认)
  • messages_en_US.properties
message = Welcome to internationalization (English)
name = Lebron James
  • messages_zh_CN.properties
message = \u6b22\u8fce\u4f7f\u7528\u56fd\u9645\u5316\uff08\u4e2d\u6587\uff09
name = \u52d2\u5e03\u6717\u002a\u8a79\u59c6\u65af

2.I18Config配置类

import java.util.Locale;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

/**
 * @author haopeng
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan

public class I18Config extends WebMvcConfigurerAdapter{
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        // 默认语言
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 参数名
        lci.setParamName("lang");
        return lci;
    }

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

3.页面

<!--这里通过thymeleaf文字国际化表达式获取信息-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="/?lang=en_US">English(US)</a>
<a href="/?lang=zh_CN">简体中文</a></br>
<p><label th:text="#{message}"></label></p>
<p><label th:text="#{name}"></label></p>
</body>
</html>

4.项目配置

##端口号
server.port=8888
##去除thymeleaf的html严格校验
spring.thymeleaf.mode=LEGACYHTML5
#设定thymeleaf文件路径 
spring.freemarker.template-loader-path=classpath:/templates

5.Controller

@Controller
public class IndexController {

    @Autowired
    private MessageSource messageSource;

    @RequestMapping("/")
    public String hello(Model model){
        Locale locale = LocaleContextHolder.getLocale();
        boolean isUs = locale.equals(Locale.US);
        return "index";
    }
}

6.补充

相关文章

网友评论

      本文标题:SpringBoot配置资源国际化

      本文链接:https://www.haomeiwen.com/subject/fczovftx.html