LocaleMessageSourceBean.java
@Component("localeResolver")
public class LocaleMessageSourceBean implements LocaleResolver
{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
//分隔符
private final String REGX="_";
@Resource
private MessageSource messageSource;
@Autowired
private MsgLanguageConfig msgLan;
/**
* 按指定的语言key获取相应的国际化信息
* @param msgKey
* @return String
*/
public String getMessage(String msgKey)
{
return messageSource.getMessage(msgKey, null,LocaleContextHolder.getLocale());
}
/**
* 按语言参数获取对应的语言配置local,默认为本地操作系统的区域语言
* @param lan
* @return
*/
private Locale getLocale(String lan)
{
//默认请求头的语言设置
Locale loc=Locale.getDefault();
String lanStr=msgLan.getLanmap().get(lan);
if(!StringUtils.isEmpty(lanStr))
{
String[] lanCty=lanStr.split(REGX);
if(lanCty.length==2)
{
loc=new Locale(lanCty[0],lanCty[1]);
}
else
{
loc=new Locale(lanCty[0]);
}
}
return loc;
}
@Override
public Locale resolveLocale(HttpServletRequest request)
{
String lan = request.getHeader(SysGlobalConst.HTTP_HEADER_X_LANG_ID);
return getLocale(lan);
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale)
{
// TODO Auto-generated method stub
//this.locale=locale;
}
}
异常枚举类BussinessErrorInfo.java
public enum BussinessErrorInfo implements IErrorInfo{
REGIST_NOT_EXIST("200001","bussinesserror.rigistnotexist")
;
private String code;
private String mgs;
BussinessErrorInfo(String code,String mgs){
this.code = code;
this.mgs = mgs;
}
@Override
public String getCode() {
return code;
}
@Override
public String getMgs() {
LocaleMessageSourceBean lmb=(LocaleMessageSourceBean) SpringContextUtil.getBean("localeResolver");
return lmb.getMessage(mgs);
}
}
controller 层调用
@RequestMapping("index")
public ResultBody index() throws Exception{
throw new GlobalErrException(BussinessErrorInfo.REGIST_NOT_EXIST);
}
配置文件:
postman 测试:
//获取当前语言类型
LocaleContextHolder.getLocale().getLanguange()