SpringBoot 国际化配置,SpringBoot Locale 国际化使用方法

http://auan.cn/java/1703.html

在项目中,很多时候需要国际化的支持,这篇文章要介绍一下springboot项目中多语言国际化的使用。
本文项目结构如图:

springboot默认就支持国际化的,而且不需要你过多的做什么配置,只需要在resources/下创建国际化配置文件即可,注意名称必须以messages开始。 messages.properties (默认的语言配置文件,当找不到其他语言的配置的时候,使用该文件进行展示)。
messages_zh_CN.properties(中文)
messages_en_US.properties(英文)

messages_zh_CN.properties   内容如下:

扫描二维码关注公众号,回复: 5536478 查看本文章
welcome = 您好,欢迎你!

messages_en_US.properties   内容如下:

welcome = hello, welcome !

在这个项目中前端页面使用的thymeleaf。创建Springboot项目不在讲述,Eclipase,IDEA创建项目都很方便快捷。pom文件记得加入 thymeleaf 支持。
pom.xml  文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.auan</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

新建IndexController:

package cn.auan.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.ui.Model;


/**
 * @author 十三月
 * @Description
 * @date 2018-08-02 下午4:57
 */
@Controller
public class IndexController {

    @Autowired
    private MessageSource messageSource;

    @RequestMapping("/")
    public String hello(Model model){

        Locale locale = LocaleContextHolder.getLocale();
        model.addAttribute("welcome", messageSource.getMessage("welcome", null, locale));

        return "index";
    }
}

到这里可以看出来,其实和整合thymeleaf一样。

然后在templates下新建index.html,代码如下:

<!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=zh_CN">简体中文</a> &nbsp;&nbsp;
    <a href="?lang=en_US">English(US)</a><br>
    <p>
        <h2 th:text="#{welcome}"></h2>
    </p>
</body>
</html>

创建国际化配置文件,LocaleConfig 代码如下:
我这里是通过Cookie方式,用Session也可以。

package cn.auan.config;

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.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.util.Locale;

/**
 * @author 十三月
 * @Description 国际化配置
 * @date 2018-08-02 下午4:57
 **/


@Configuration
@EnableAutoConfiguration
@ComponentScan
public class LocaleConfig extends WebMvcConfigurerAdapter {

    //Cookie
    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setCookieName("localeCookie");
        //设置默认区域
        localeResolver.setDefaultLocale(Locale.ENGLISH);
        localeResolver.setCookieMaxAge(3600);//设置cookie有效期.
        return localeResolver;
    }



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

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



}

现在启动项目,访问 http://localhost:8080/
然后点击中文或者English就可以自由切换语言了。
springboot-i18n 国际化

项目包下载路径:https://gitee.com/xueleilei/Springboot-internationalization

https://zhoujian1982318.iteye.com/blog/1725685

1、 版本 Spring 3.1

 

2、 配置 LocaleResolver

 

 

LocaleResolver 是指用什么策略来检测请求是哪一种Local, Spring 提供以下几种策略:

 

2.1、AcceptHeaderLocaleResolver

根据浏览器Http Header中的accept-language域判定(accept-language域中一般包含了当前操作系统的语言设定,可通过HttpServletRequest.getLocale方法获得此域的内容)。 改变Local 是不支持的,即不能调用LocaleResolver接口的 setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale); 方法设置Local.
2.2、SessionLocaleResolver
    根据用户本次会话过程中的语言设定决定语言种类(如:用户登录时选择语言种类,则此次登录周期内统一使用此语言设定)。

2.3、CookieLocaleResolver
根据Cookie判定用户的语言设定(Cookie中保存着用户前一次的语言设定参数)。

 

2.4、FixedLocaleResolver 一直使用固定的Local, 改变Local 是不支持的 见(2.1)

 

如果需要使用哪一种策略,只需在DispatcherServlet 指定的Spring配置文件中配置就行, 例如需要使用CookieLocalResolver , 在配置文件如下配置:

 

< bean id = "localeResolver" class = "org.springframework.web.servlet.i18n.CookieLocaleResolver" ></bean >

 

DispatchServlet 将在初始化的时候, 会调用initLocaleResolver(context) 方法去配置文件中找名字为“localeResolver" bean. 如果有就用配置文件配置的localResolver. 如果没有配置将用默认的localResolver "AcceptHeaderLocaleResolver".

 

3、使用Spring MVC时,  controller如何得到请求的 Local

 

DispatchServlet 会在 processRequest(HttpServletRequest request, HttpServletResponse response) 方法中设置LocaleContext, 把LocalContext 和当前线程关联起来. 代码如下:

 

LocaleContextHolder.setLocaleContext (buildLocaleContext(request), this. threadContextInheritable );

 

DispatchServlet 中buildLocalContext代码如下:

 

 

protected LocaleContext buildLocaleContext( final HttpServletRequest request) {

        return new LocaleContext() {

            public Locale getLocale() {

                return localeResolver .resolveLocale(request);

            }

            @Override

            public String toString() {

                return getLocale().toString();

            }

        };

}

 

这里的Local通过localResolver 解析得到,  localResolver 即是从Spring 配置文件配置的localResolver, 默认是"AcceptHeaderLocaleResolver".

 

如果你想要在 controller 中得到当前请求的Local,  代码可以如下写:

 Locale locale = LocaleContextHolder.getLocale();

 

或者你可以用Spring 中的RequestContextUtils 类方法getLocal得到 request 中保存的localResolver, 并用localResolver 解析得到Local.   代码如下:

 

 

public static Locale getLocale (HttpServletRequest request) {

        LocaleResolver localeResolver = getLocaleResolver (request);

        if (localeResolver != null ) {

            return localeResolver.resolveLocale(request);

        }

        else {

            return request.getLocale();

        }

}

 

localResolver 会在DispatcherServlet的doService 方法中,将localResolver保存到request 属性中 代码如下:

 

request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);

 

 

4、LocaleChangeInterceptor 的使用:

 

如果想要用户能改变Local, 我们需要配置 LocaleChangeInterceptor, 这个拦截器将检查传入的请求,如果请求中有“local" 的参数(参数可以配置),如http://localhost:8080/test?local=zh_CN. 该Interceptor将使用localResolver改变当前用户的

Local, 代码如下:

 

 

String newLocale = request.getParameter( this paramName );

if (newLocale != null ) {

  LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver (request);

  if (localeResolver == null ) {

      throw new IllegalStateException( "No LocaleResolver found: not in a ..." );

  }

    //改变当前的Local

  localeResolver.setLocale (request, response, StringUtils.parseLocaleString (newLocale));

}

 

要使得LocaleChangeInterceptor 有效果,在Spring 的配置文件加入即可:

 

 

< mvc:interceptors >

     < bean class = "org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/ >

</ mvc:interceptors >

猜你喜欢

转载自blog.csdn.net/yb223731/article/details/85252334
今日推荐