- 准备国际化文件
资源目录下创建 i18文件夹,
i18 下面创建两个文件: 预配置信息
messages_en_US.preperties | success=success
messages_zh_CN.properties | success=操作成功
- 在application.yml中指定国际化文件的位置
spring:messages:basename: i18/messages
- 创建一个自定义 local 解析器
package com.shi.demo.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;@Component
public class CustomLocalResolver implements LocaleResolver {@Autowiredprivate HttpServletRequest request;public Locale getLocale() {return resolveLocale(request);}@Overridepublic Locale resolveLocale(HttpServletRequest request) {Cookie[] cookies = request.getCookies();if (ObjectUtils.isEmpty(cookies)) {return Locale.getDefault();}List<Cookie> cookieList = Arrays.stream(request.getCookies()).filter(cookie -> cookie.getName().equals("locale")).collect(Collectors.toList());if (ObjectUtils.isEmpty(cookieList)) {return Locale.getDefault();}Locale locale = StringUtils.parseLocale(cookieList.get(0).getValue());if (ObjectUtils.isEmpty(locale)){return Locale.getDefault();}return locale;}@Overridepublic void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {}}
- 准备工具类。
使用Set注入解决 静态属性不能注入的问题。
package com.shi.demo.utils;import com.shi.demo.config.CustomLocalResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;@Component
public class I18Utils {private static CustomLocalResolver localResolver;private static ApplicationContext context;public static String getMessage(String code,Object[] args){return context.getMessage(code,args,localResolver.getLocale());}@Autowiredpublic void setLocalResolver(CustomLocalResolver localResolver) {I18Utils.localResolver = localResolver;}@Autowiredpublic void setContext(ApplicationContext context) {I18Utils.context = context;}
}
- 测试 代码
@RestController
@RequestMapping("/users")
public class UserController {@GetMappingpublic String get() {return "get请求:"+I18Utils.getMessage("success",null);}
}
- 发起请求
使用的是idea 自带的http client 发送的请求
###
GET http://localhost:8080/users
#Cookie: locale=zh-cn # 由于上面使用了StringUtils.parseLocale(),所以这里的值不区分大小写以及‘_’和‘-’
Cookie: locale=en_US