java springboot i18n

SpringBoot快速配置多語系(國際化)

許文 Richard Hsu 2020/12/30 19:37:00
7317

一、前言

   多語系網站的好處:

    在網路世界裡,使用者沒辦法親眼看到公司實際的樣子,官網就是一個形象的展現,網站有不同的語系除了更顯國際化,頁面的瀏覽上也顯得更親切;對很多人來說,使用自己不熟悉的語言,會感覺陌生,容易產生不信任感。若能讓潛在客戶使用自己語言瀏覽網站,也能讓訪客覺得這家公司是一間相當有規模的公司,提高在網站上的體驗,也有機會提高轉化率

 

二、Spring boot多語系介紹、環境配置

    Spring Boot自動配置MessageSourcei18n多國語言訊息,不用再自己配置MessageSourcebean且預設會尋找classpath根目錄下名稱為messagesproperties作為訊息來源。如果想要使用其他名稱或路徑,可在Spring Boot配置檔application.properties設定。

 

      範例環境:

      n  Java 8

      n  Spring Boot 2.2.6.RELEASE

      n  Maven

 

 

三、配置多語系

      1.添加依賴

 

      n  pom.xml添加如下依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
		
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.73</version>
</dependency>

 

      2.   創建.propertis言包

l  message.properties

l  message_en_US.properties

l  message_zh_TW.properties

          

 

 

      3. 設置messages訊息內容

      l  messages.properties

     current.locale=中文(預設)

         

 

      l  messages_zh_TW.properties

     current.locale=中文

         

 

      l  messages_en_US.properties

     current.locale=English

   

 

      4.配置application.properties

spring.messages.basename=i18n/messages

spring.messages.encoding=UTF-8

spring.messages.cache-duration=3600

 

      5.創建解析器和攔截器

 

       l解析器:

                   其中locale表示默認語言,當請求中未包含語種信息,則設置默認語種,當前默認為TAIWAN, zh_TW

 

      l攔截器:

 

  默認攔截器 其中lang表示切換語言的參數名。

 

package com.demo.config;
import java.util.Locale;

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

@Configuration
public class WebConf implements WebMvcConfigurer { 

    /**
     * 默認解析器 其中locale表示默認語言,當請求中未包含語種信息,則設置默認語種
     * 當前默認為TAIWAN, zh_TW
     */   
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.TAIWAN);
        return slr;
    }

    /**
    * 默認攔截器 其中lang表示切換語言的參數名
    */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(localeChangeInterceptor());
    }
}

 

      6.編寫Controller

@Controller
@RequestMapping("/test")
public class DemoController {
	
	@Autowired
	private MessageSource messageSource;
	
	 /**
	 * 取得當前語系.
	 *
	 * @param rq the rq
	 * @param request the request
	 * @return the string
	 */
	@RequestMapping(value = { "/getCurrentLocale" }, method = { RequestMethod.GET }, consumes = {MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public ResponseEntity<JSONObject> changeLocale(HttpServletRequest request, HttpServletResponse response) {
		Locale locale = LocaleContextHolder.getLocale();
		
		JSONObject json = new JSONObject();
		json.put("locale", "當前語系:" + messageSource.getMessage("current.locale", null, locale));

		return new ResponseEntity<JSONObject>(json, HttpStatus.OK);
	}
}

 

      7.配置SpringBootApplication啟動server

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

 

      啟動server

      

 

      8.  Postman 測試

  l  zh_TW

      

  l  en_US

      

 

四、目錄結構

目錄結構

─src
 └─main
    ├─java
    │  └─com
    │      └─demo
    │              │  DemoApplication.java
    │              └─config
    │                     WebConf.java
    │              │
    │              └─controller
    │                      DemoController.java
    │
    └─resources
        │  application.properties
        └─i18n
           │  messages.properties
           │  messages_zh_TW.properties
           │  messages_en_US.properties

 

 

完整程式碼請參考github

  

參考來源:https://phrase.com/blog/posts/spring-boot-internationalization/

許文 Richard Hsu