Spring Boot 提供了很好的国际化支持,可以轻松地实现中英文国际化。
项目创建,及其springboot系列相关知识点详见:springboot系列
springboot系列,最近持续更新中,如需要请关注
如果你觉得我分享的内容或者我的努力对你有帮助,或者你只是想表达对我的支持和鼓励,请考虑给我点赞、评论、收藏。您的鼓励是我前进的动力,让我感到非常感激。
文章目录
- 1 创建properties国际化文件
- 2 创建异常码(和国际化文件有关联关系)
- 3 使用
- 4 测试效果
1 创建properties国际化文件
在 src/main/resources 目录下创建多个属性文件(.properties),每个文件对应一种语言
messages_en_US.properties
# 系统状态码 ============================================================================================================
error.20000=The request is successful.
error.40000=Param error!
error.50000=System error!
messages_zh_CN.properties
# 系统状态码 ============================================================================================================
error.20000=请求成功.
error.40000=参数错误!
error.50000=系统异常!
**注:**demo截图
2 创建异常码(和国际化文件有关联关系)
GlobalError
/**
* 系统异常码枚举
*
* @author w30009430
* @since 2023 -09-05 12:03
*/
public enum GlobalError {
// 系统状态码 ====================================================================================================
/**
* Success ai model error.
*/
SUCCESS(20000),
/**
* Param error ai model error.
*/
PARAM_ERROR(40000),
/**
* Exception ai model error.
*/
EXCEPTION(50000);
/**
* The Code.
*/
int code;
GlobalError(int code) {
this.code = code;
}
/**
* Gets code.
*
* @return the code
*/
public int getCode() {
return code;
}
/**
* Gets message.
*
* @return the message
*/
public String getMessage() {
return I18nUtils.getMsgByErrorCode(code);
}
/**
* Gets message with params.
*
* @param supplementMsg the supplement msg
* @return the message with params
*/
public String getMessageWithParams(String supplementMsg) {
return I18nUtils.getI18nErrorMsg(code, supplementMsg, CookieUtil.getLanguage());
}
/**
* Gets message en with params.
*
* @param supplementMsg the supplement msg
* @return the message en with params
*/
public String getMessageEnWithParams(String supplementMsg) {
return I18nUtils.getI18nErrorMsg(code, supplementMsg, Constants.Other.EN);
}
/**
* Gets message cn with params.
*
* @param supplementMsg the supplement msg
* @return the message cn with params
*/
public String getMessageCnWithParams(String supplementMsg) {
return I18nUtils.getI18nErrorMsg(code, supplementMsg, Constants.Other.ZH);
}
}
CookieUtil
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.net.HttpCookie;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class CookieUtil {
private static final String ZH = "zh";
private static final String EN = "en";
private static final String CN = "cn";
private static final String US = "us";
private static final String ZH_CN = "zh_cn";
private static final String LANG = "lang_key";
public CookieUtil() {
}
public static String getLanguage() {
return decideLocaleInfoFromCookie("en", "zh");
}
public static String getCountry() {
return decideLocaleInfoFromCookie("us", "cn");
}
private static String decideLocaleInfoFromCookie(String defaultEnValue, String cnValue) {
HttpServletRequest request = getRequest();
Cookie[] cookies = null;
if (request != null) {
cookies = getCookies(request);
}
if (cookies != null) {
Cookie[] var4 = cookies;
int var5 = cookies.length;
for (int var6 = 0; var6 < var5; ++var6) {
Cookie cookie = var4[var6];
if ("lang_key".equals(cookie.getName()) && "zh_cn".equals(cookie.getValue())) {
return cnValue;
}
}
}
return defaultEnValue;
}
public static Cookie[] getCookies(HttpServletRequest request) {
Cookie[] cookies = null;
if (request.getCookies() != null) {
cookies = request.getCookies();
} else {
String cookieStr = request.getHeader("cookie");
if (StringUtils.isNotBlank(cookieStr)) {
cookies = (Cookie[]) HttpCookie.parse(cookieStr).stream().map((httpCookie) -> {
return new Cookie(httpCookie.getName(), httpCookie.getValue());
}).toArray((x$0) -> {
return new Cookie[x$0];
});
}
}
return cookies;
}
public static String getCountryByLanguage(String language) {
String country = "us";
if ("zh".equals(language)) {
country = "cn";
}
return country;
}
public static HttpServletRequest getRequest() {
HttpServletRequest request = null;
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if (attributes != null && attributes instanceof ServletRequestAttributes) {
request = ((ServletRequestAttributes) attributes).getRequest();
}
return request;
}
}
I18nUtils
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 功能描述
*
* @author w30009430
* @since 2023 -09-05 12:03
*/
@Slf4j
public class I18nUtils {
/**
* Gets i 18 n error msg.
*
* @param code the code
* @param supplementMsg the supplement msg
* @param language the language
* @return the i 18 n error msg
*/
public static String getI18nErrorMsg(int code, String supplementMsg, String language) {
String key = "error." + code;
String message = getMsgByLanguage(key, language);
if (StringUtils.isNotEmpty(message)) {
message = message + " " + supplementMsg;
}
return message;
}
private static String getMsgByLanguage(String key, String language) {
String country = getCountryByLanguage(language);
ResourceBundle bundle = null;
String value = null;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
return getMsg(key, language, country, value, contextClassLoader);
}
private static String getMsg(String key, String language, String country, String value, ClassLoader contextClassLoader) {
ResourceBundle bundle;
try {
if (contextClassLoader != null) {
bundle = ResourceBundle.getBundle("i18/messages", new Locale(language, country), contextClassLoader);
} else {
bundle = ResourceBundle.getBundle("i18/message", new Locale(language, country));
}
if (bundle != null) {
value = bundle.getString(key);
}
} catch (MissingResourceException var8) {
log.error("missing resource error !");
}
return value;
}
private static String getCountryByLanguage(String language) {
String country = "us";
if ("zh".equals(language)) {
country = "cn";
}
return country;
}
public static String getMsgByErrorCode(int code) {
ClassLoader classLoader = null;
if (code > 10000) {
classLoader = Thread.currentThread().getContextClassLoader();
}
String key = "error." + code;
String language = CookieUtil.getLanguage();
String country = CookieUtil.getCountry();
String value = null;
return getMsg(key, language, country, value, classLoader);
}
}
3 使用
DemoController
@Api(tags = {"Swagger2测试-demo测试类"})
@RestController
@RequestMapping("/demo")
public class DemoController {
@ApiOperation(value = "Hello测试", notes = "无参数测试")
@GetMapping("/hello")
public RespResult hello() {
return RespResult.resultOK("OK");
}
}
RespResult
@Data
public class RespResult {
/**
* The Code.
*/
int code = RespCodeEnum.SUCCESS.getCode();
/**
* The Data.
*/
Object data;
/**
* The Msg.
*/
String msg;
/**
* 处理请求响应正常时方法
*
* @param data 返回的数据
* @return RespResult 数据
*/
public static RespResult resultOK(Object data) {
RespResult respResult = new RespResult();
respResult.data = data == null ? new HashMap<>() : data;
respResult.msg = GlobalError.SUCCESS.getMessage();
return respResult;
}
/**
* 处理请求异常时方法
*
* @param code 状态码
* @param msg 异常信息
* @param data 数据
* @return RespResult data
*/
public static RespResult resultFail(int code, String msg, Object data) {
RespResult respResult = new RespResult();
respResult.code = code;
respResult.msg = msg;
respResult.data = data;
return respResult;
}
/**
* 处理请求异常时方法
*
* @param code 状态码
* @param msg 异常信息
* @return RespResult data
*/
public static RespResult resultFail(int code, String msg) {
RespResult respResult = new RespResult();
respResult.data = new HashMap<>();
respResult.code = code;
respResult.msg = msg;
return respResult;
}
}
RespCodeEnum
public enum RespCodeEnum {
SUCCESS(200, "The request is successful.", "请求成功."),
EXP(500, "System error! ", "系统异常!");
private Integer code;
private String descEn;
private String descCn;
RespCodeEnum(final int code, final String descEn, final String descCn) {
this.code = code;
this.descEn = descEn;
this.descCn = descCn;
}
/**
* <设置code值>
*
* @return Integer 数据
*/
public Integer getCode() {
return code;
}
/**
* <获取导入校验枚举描述>
*
* @return Integer 数据
*/
public String getDescEn() {
return descEn;
}
/**
* <获取导入校验枚举描述>
*
* @return Integer 数据
*/
public String getDescCn() {
return descCn;
}
}
4 测试效果
中文:
英文-默认: