最近注意到许多项目都是支持语种切换的,于是用springboot实现了前后端分离的语种切换
依赖
在pom.xml中添加如下依赖
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery-i18n-properties</artifactId>
<version>1.2.7</version>
</dependency>
开始配置
说到配置就令人头疼,所幸的是springboot极大的简化了开发中繁琐的配置。
1.创建.propertis语言包
- message.properties
- message_en_US.properties
- message_zh_CN.properties
命名规则:前缀_语种类型.properties
,其中message.properties
文件内容可为空。但必须定义
。该文件优先级最高
添加内容
由于文件格式非UTF-8,我这里将汉字转为了unicode字符,但这并不影响读取。message.properties
中未定义任何内容。
2.在application.properties中添加如下内容
#i18n
spring.messages.basename=static.i18n.message
spring.messages.cache-duration=3600
spring.messages.encoding=UTF-8
其中最主要的是basename,指定了语言包所在位置。
basename的值结尾最后需要加上properties语言包文件名的前缀
3.创建解析器和拦截器
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 LocaleConfig {
/**
* 默认解析器 其中locale表示默认语言,当请求中未包含语种信息,则设置默认语种
* 当前默认为CHINA,zh_CN
*/
@Bean
public SessionLocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.CHINA);
return localeResolver;
}
/**
* 默认拦截器 其中lang表示切换语言的参数名
* 拦截请求,获取请求参数lang种包含的语种信息并重新注册语种信息
*/
@Bean
public WebMvcConfigurer localeInterceptor() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor);
}
};
}
}
localeResolver
其中定义了默认语种。localeInterceptor
前端请求参数lang中包含指定语种时,将该语种注册到Locale中
4.编写控制器
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/domain")
//解决跨域问题:指定允许跨域的域名
@CrossOrigin(origins = "http://test.do")
public class DomainControl {
@Autowired
private MessageSource messageSource;
/**
* 多语言测试
*/
@RequestMapping("/i18ntest")
public Map<Object, Object> i18nTest() {
Map<Object, Object> result = new HashMap<Object, Object>();
result.put("code", 5001);
result.put("msg", messageSource.getMessage("error.error_5001", null, LocaleContextHolder.getLocale()));
return result;
}
}