SpringBoot国际化:创建多语言支持的Web应用
SpringBoot国际化:创建多语言支持的Web应用
介绍
SpringBoot作为一个强大的框架,提供了便捷的国际化支持,使开发者能够轻松创建多语言支持的Web应用。通过使用SpringBoot的MessageSource,开发者可以在应用中实现动态的语言切换。
设置国际化
- 添加依赖,springboot相关依赖
- 添加配置文件
- yml文件
spring:
messages:
basename: i18n/messages
encoding: UTF-8
注意:basename后面的messages位配置文件后面Resource Bundle后面的名字
- 通过拦截器+aop,实现拦截请求做到国际化
- i18n配置
@Configuration
public class I18nConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
//设置默认语言,美式英文
slr.setDefaultLocale(Locale.US);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
//参数名与前端方法携带参数名一致
lci.setParamName("Accept-Language");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
- 拦截器,拦截所有请求
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyRequestInterceptor())
.addPathPatterns("/**");
}
}
- aop
通过aop拦截到想要拦截所有请求的返回值,并根据前端传来的language进行国际化配置。
- 获取到语言
- 修改返回值,通过code找到对应的name,这个我都存在一个枚举类中
- 通过name找到配置文件中对应的配置,并取出,修改返回值
@Aspect
@Component
public class ChangeLanguageAspect {
private static final Logger logger = LoggerFactory.getLogger(ChangeLanguageAspect.class);
private static final Map<String, Locale> map = new HashMap(){
{
put("zh_CN", Locale.SIMPLIFIED_CHINESE);
put("en_US", Locale.US);
put("zh_TW", Locale.TRADITIONAL_CHINESE);
put("th_TH", new Locale("th", "TH"));
put("default", Locale.getDefault());
}
};
@Resource
private MessageSource messageSource;
@Resource
private LocaleResolver localeResolver;
@Pointcut("within(@org.springframework.web.bind.annotation.RestController *) || within(@org.springframework.stereotype.Controller *)")
public void i18nPointCut() {}
@AfterReturning(pointcut = "i18nPointCut()", returning = "result")
public void doAfterReturning(Object result) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
// 获取语言
String language = MyRequestInterceptor.REQUEST_ID_THREAD_LOCAL.get();
if (StringUtil.isEmptyWithTrim(language) || !map.containsKey(language)){
language = "default";
}
localeResolver.setLocale(request, response, map.get(language));
Locale locale = LocaleContextHolder.getLocale();
System.out.println(locale);
// 修改返回,获取到返回值code,找到对应的name,从而在配置文件中找到对应的字段
ServiceResponse<?> serviceResponse = (ServiceResponse<?>) result;
int code = serviceResponse.getCode();
GlobalErrorCode globalErrorCode = GlobalErrorCode.fromCode(code);
String apiServiceError = messageSource.getMessage(globalErrorCode.name(), null, locale);
logger.info("info,{}",apiServiceError);
logger.info("result,{}",result);
((ServiceResponse<?>) result).setMessage(apiServiceError);
}
}