这里使用 请求头参数 设置语言地区,也可以根据 客户端IP识别地区
import com.mh.jishi.i18n.LanguageMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* 多语言拦截器
*
*
*
*
* @author 扫楼 <[email protected]>
* @since 2020年11月18日 17:11
*/
@Order(1)
public class LocalInterceptor implements HandlerInterceptor {
private final Logger log = LoggerFactory.getLogger(LocalInterceptor.class);
/**
* 获取请求头参数设置 语种,请参考:{@link LanguageMessage#init()}
* 请求头 lang 有效值:
* zh_CN - 中文
* en_US - 英文
*
* @param request current HTTP request
* @param response current HTTP response
* @param handler chosen handler to execute, for type and/or instance evaluation
* @return true
*
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 根据请求头参数 切换地区
String nowLang = request.getHeader("lang");
if (StringUtils.isBlank(nowLang)) {
// 设置默认地区为 中国 zh_CN
LocaleContextHolder.setLocale(Locale.CHINA);
} else if (nowLang.equalsIgnoreCase("zh_CN") || nowLang.equalsIgnoreCase("zh")) {
// 中文
LocaleContextHolder.setLocale(Locale.CHINA);
} else if (nowLang.equalsIgnoreCase("en_US") || nowLang.equalsIgnoreCase("en")) {
// 英语
LocaleContextHolder.setLocale(Locale.US);
}else{
// 设置默认地区为 中国 zh_CN
LocaleContextHolder.setLocale(Locale.CHINA);
}
log.info("当前语言:【{}】, 地区:【{}】", nowLang, LocaleContextHolder.getLocale());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
import com.mh.jishi.interceptor.CurrentLimitingInterceptor;
import com.mh.jishi.interceptor.LocalInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
*
* web 配置
*
*
* @author 扫楼 <[email protected]>
* @since 2020年11月18日 17:11
*/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 加入 swagger-ui.html 映射,不然会 404找不到页面
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// 加入 swagger-ui.html 映射 结束
super.addResourceHandlers(registry);
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// 添加 语言地区拦截器
registry.addInterceptor(new LocalInterceptor());
super.addInterceptors(registry);
}
}
/**
* 语言消息接口
*
*
*
*
* @author 扫楼 <[email protected]>
* @since 2020年11月18日 17:11
*/
public interface BaseLanguageMessage {
/**
* @return 获取 "请求成功" 对应语种消息
*/
String getSuccessRequestMessage();
/**
* @return 获取 "系统繁忙!请稍后重试" 对应语种消息
*/
String getTimeOutRequestMessage();
/**
* @return 获取 "请求失败" 对应语种消息
*/
String getFailedRequestMessage();
}
/**
* 中文语言
*
*
*
*
* @author 扫楼 <[email protected]>
* @since 2020年11月18日 17:11
*/
public class ZhCnLanguageMessage implements BaseLanguageMessage{
@Override
public String getSuccessRequestMessage() {
return "请求成功";
}
@Override
public String getTimeOutRequestMessage() {
return "系统繁忙!请稍后重试";
}
@Override
public String getFailedRequestMessage() {
return "请求失败";
}
}
package com.mh.jishi.i18n;
/**
* 英文语言
*
*
*
*
* @author 扫楼 <[email protected]>
* @since 2020年11月18日 17:11
*/
public class EnUsLanguageMessage implements BaseLanguageMessage{
@Override
public String getSuccessRequestMessage() {
return "Request successful";
}
@Override
public String getTimeOutRequestMessage() {
return "The system is busy! Please try again later";
}
@Override
public String getFailedRequestMessage() {
return "Request failed";
}
}
import com.mh.jishi.interceptor.LocalInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Locale;
/**
* 初始化语言配置
* 配套拦截器使用 {@link LocalInterceptor}
*
*
*
*
* @author 扫楼 <[email protected]>
* @since 2020年11月18日 17:11
*/
@Component
public class LanguageMessage {
private static HashMap<Locale, BaseLanguageMessage> messageHashMap;
private final Logger logger = LoggerFactory.getLogger(LanguageMessage.class);
private LanguageMessage(){}
@PostConstruct
public void init(){
logger.info("开始初始化语言信息");
messageHashMap = new HashMap<>();
messageHashMap.put(Locale.CHINA, new ZhCnLanguageMessage());
messageHashMap.put(Locale.US, new EnUsLanguageMessage());
logger.info("完成初始化语言信息");
}
public static BaseLanguageMessage getLanguageMessage(){
return messageHashMap.get(LocaleContextHolder.getLocale());
}
}
@getMapping("/testLanguage")
public String logout() {
return LanguageMessage.getLanguageMessage().getSuccessRequestMessage();
}
我不使用 Spring i18实现 主要是因为 我的需求要 语言是动态的,可以随意增删改查,后续可以将语言存入数据库或者缓存,因为 i18n 多语言实现也是 key - value 方式