• Springboot国际化案例


    实现功能

    1. 默认根据浏览器Accept-Language中的语言信息判断选择语言版本;

    2. 提供切换语言按钮URL?lang=zh_CN,切换后将语言信息存入cookie;
      例如:http://localhost:8080/show?language=zh_CN

    3. 若客户浏览器中存在语言cookie则优先使用coolie选择显示语言;

    1.导入环境依赖

    
        <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-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.72</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
    
        </dependencies>
    
    

    2.创建国际化的配置文件

    image

    默认对应信息

    200=成功{0}
    500=內部异常
    name=用户名
    pwd=密码
    

    中文对应信息

    200=成功
    500=內部异常
    name=用户名
    pwd=密码
    

    英文对应信息

    200=success
    500=unexpected exception
    name=user name
    pwd=password
    

    3.配置文件,指定国际化的参数,这一步容易忘记

    spring:
      messages:
        basename: i18n/messages/messages
        encoding: UTF-8
        fallbackToSystemLocale: false
    
      thymeleaf:
        mode: HTML
        encoding: UTF-8
        servlet:
          content-type: text/html
        cache: false
    
    

    这里spring.messages.basename的路径是根据上面创建的国际化文件名来的

    配置完成之后,就可以通过代码实现从几个国际化配置文件中由key获得value值了
    image

    4.封装一个MessageSource工具类,用于获取不同语言下的value值。这个是核心类,其实到这一步国际化的功能就已经实现完了,可以直接调用实现了。后面的一个拦截器类是优化体验的,可以没有。

    package com.example.demo.util;
    
    import org.springframework.context.MessageSource;
    import org.springframework.context.i18n.LocaleContextHolder;
    import org.springframework.stereotype.Component;
    
    import java.util.Locale;
    
    /**
     * @author lyd
     * @Description: 国际化的核心类,主要就是通过这个类来获取不同语言的value信息
     * @date 13:59
     */
    @Component
    public class MessageSourcUtil {
    
    	/**
    	 * 设置默认语言环境为中文
    	 */
    	public static final Locale DEF_LOCALE = Locale.CHINA;
    
    	private static MessageSource messageSource;
    
    	public MessageSourcUtil(MessageSource messageSource) {
    		MessageSourcUtil.messageSource = messageSource;
    	}
    
    
    	/**
    	 * @param code key值,通过这个来获取不同语言下的value
    	 * @param args 这是传入的占位符,可以为空
    	 * @return {@link String}
    	 */
    	public static String getMessage(String code, Object... args) {
    		// 获得当前的语言环境
    		Locale locale = LocaleContextHolder.getLocale();
    		if (locale == null) {
    			locale = DEF_LOCALE;
    		}
    		return messageSource.getMessage(code, args, locale);
    	}
    
    	public static String getMessage(Locale locale, String code, Object... args) {
    		return messageSource.getMessage(code, args, locale);
    	}
    
    }
    

    5.添加个拦截器,有拦截器可以不用每次都传入语言参数,省事很多

    package com.example.demo.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.CookieLocaleResolver;
    import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
    
    
    /**
     * @author lyd
     * @Description:
     * @date 14:50
     */
    @Configuration
    public class AutoConfig implements WebMvcConfigurer {
    	/**
    	 * 这个如果不存在,则会抛异常: nested exception is java.lang.UnsupportedOperationException: Cannot change HTTP accept header - use a different locale resolution strategy
    	 *
    	 * @return
    	 */
    	@Bean
    	public LocaleResolver localeResolver() {
    		// 也可以换成 SessionLocalResolver, 区别在于国际化的应用范围
    		CookieLocaleResolver localeResolver = new CookieLocaleResolver();
    		return localeResolver;
    	}
    
    	/**
    	 * 根据请求参数,来设置本地化
    	 *
    	 * @return
    	 */
    	@Bean
    	public LocaleChangeInterceptor localeChangeInterceptor() {
    		LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    		localeChangeInterceptor.setParamName("language");
    		return localeChangeInterceptor;
    	}
    
    
    	/**
    	 * 添加拦截器
    	 *
    	 * @param interceptorRegistry 拦截器注册
    	 */
    	@Override
    	public void addInterceptors(InterceptorRegistry interceptorRegistry) {
    		interceptorRegistry.addInterceptor(localeChangeInterceptor());
    	}
    }
    

    6.写一个接口类测试

    package com.example.demo.controller;
    import com.example.demo.util.MessageSourcUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.MessageSource;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    
    @Controller
    public class TestController {
    	
    	@Autowired
    	MessageSource messageSource;
    
    	@GetMapping(path = "show")
    	public String show() {
    		System.out.println("得到国际化配置文件中的value值:");
    		System.out.println(MessageSourcUtil.getMessage("200"));
    		System.out.println(MessageSourcUtil.getMessage("500"));
    		System.out.println(MessageSourcUtil.getMessage("name"));
    		System.out.println(MessageSourcUtil.getMessage("pwd"));
    		return "index";
    	}
    
    }
    

    测试

    输入http://localhost:8080/show
    image

    输入http://localhost:8080/show
    image

    项目源码

    https://github.com/Wranglery/test-i18n

  • 相关阅读:
    C语言 · 最小公倍数
    SSH实战 · SSH项目开发环境搭建
    C语言 · 回文数
    C语言 · 特殊回文数
    C语言 · 查找整数
    SSH实战 · SSH项目中怎么玩验证码
    SSH实战 · JAVA发送邮件相关
    SSH实战 · AJAX异步校验
    C语言 · 打印1-200之间的素数
    Jenkins权限设计错误解决办法
  • 原文地址:https://www.cnblogs.com/lyd447113735/p/14986258.html
Copyright © 2020-2023  润新知