使用的SpringBoot版本是2.3.5
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
</parent>
一、简单测试
(1)、配置文件
messages:
basename: i18n/messages
encoding: UTF-8
或者使用 Bean进行代码配置
@Configuration
public class LocalMessageConfig {
/**
* 系统国际化文件配置
* @return MessageSource
*/
@Bean(name = "messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setBasenames("i18n/messages");
return resourceBundleMessageSource;
}
}
(2)、在resource目录下i18n文件夹,文件夹下建三个文件,文件名与配置文件中的basename中名称一致,在这里都是messages
message.properties文件内容:
login.fail = {0} 登陆失败
message_en_US.properties文件内容:
login.fail = {0} login fail
message_zh_CN.properties文件内容:
login.fail = {0} 登陆失败
(3)、测试
@RequestMapping("/hello")
@RestController
public class I18nController {
@Autowired
private MessageSource messageSource;
@GetMapping
public String msg(){
String stringMsg1 = messageSource.getMessage("login.fail",new Object[]{username},Locale.CHINA);
String stringMsg2 = messageSource.getMessage("login.fail",new Object[]{username},Locale.US);
System.out.println("stringMsg1---"+stringMsg1 +"\n" + "stringMsg2---"+stringMsg2);
//Locale locale = LocaleContextHolder.getLocale();
//String message = messageSource.getMessage("login.fail", new Object[]{username}, locale);
}
}
stringMsg1---admin 登陆失败
stringMsg2---admin login fail
工具
@Component
public class MessageUtils {
@Autowired
private MessageSource messageSource;
public MessageUtils(MessageSource messageSource) {
this.messageSource = messageSource;
}
public String getMessage(String msgKey, Object[] args) {
return messageSource.getMessage(msgKey, args, LocaleContextHolder.getLocale());
}
public String getMessage(String msgKey) {
return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
}
}
二、添加拦截
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Value("${spring.cors.allowedOrigins:*}")
private String allowedOrigins;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*", "Authorization")
.allowCredentials(false)
.maxAge(3600);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String language = request.getParameter("Language");
Locale locale;
if (language != null && !language.isEmpty()) {
locale = Locale.forLanguageTag(language);
} else {
locale = Locale.US;
}
LocaleContextHolder.setLocale(locale);
return true;
}
});
}
}
三、全局异常处理
@Slf4j
@ControllerAdvice
public class BaseExceptionHandler {
@Resource
private MessageSource messageSource;
/**
* 处理自定义异常
* @param response
* @param e
*/
@ResponseBody
@ExceptionHandler(ServiceException.class)
public void handleServiceException(HttpServletResponse response, ServiceException e) {
log.error("ServiceException:{}", e.getMessage(), e);
String message = e.getMessage();
String trMessage = e.getMessage();
Locale locale = LocaleContextHolder.getLocale();
String s = locale.toString();
if(s.contains("en")){
// 设置Locale为中文(简体中文)
Locale chineseLocale = Locale.SIMPLIFIED_CHINESE;
// 使用ResourceBundle加载中文(简体中文)的资源束
ResourceBundle bundle = ResourceBundle.getBundle("i18n/message", chineseLocale);
// 获取资源束中的所有键值对
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
String value = bundle.getString(key);
if(value.equals(message)){
trMessage = messageSource.getMessage(key, null, Locale.US);
break;
}
}
}
print(response, JSONObject.toJSONString(ResponseMessage.error(e.getCode(), e.getStatus(), trMessage)));
}
/**
* 处理其他异常
* @param response
* @param e
*/
@ResponseBody
@ExceptionHandler(Exception.class)
public void handleException(HttpServletResponse response, Exception e) {
log.error("Exception:{}", e.getMessage(), e);
print(response, JSONObject.toJSONString(ResponseMessage.error()));
}
/**
* 返回异常到前端
* @param response
* @param result
*/
private void print(HttpServletResponse response, String result) {
try {
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(result);
} catch (Exception e) {
log.error("httpServletResponse print fail:{}", e.getMessage(), e);
}
}
}