如何在controller中自动获取国际化资源文件中的值?

@AutowiredprivateMessageSourcemessageSource;这种方式在调用getMessage()方法是需要穿locale参数;Request... @Autowired
private MessageSource messageSource;
这种方式在调用getMessage()方法是需要穿locale参数;
RequestContext requestContext = new RequestContext(request);

这种手动获取更不方便了。
如何在controller中自动获取国际化资源文件中的值?
spring mvc
展开
 我来答
maye100
推荐于2016-05-05 · TA获得超过2651个赞
知道小有建树答主
回答量:1341
采纳率:100%
帮助的人:1005万
展开全部

你所谓的自动是根据什么条件判断的呢?

一般两种:

  1. 根据浏览器的语言进行设置;

  2. 根据用户信息(保存在数据库中)来设置;

第一种你要用js把浏览器的语言传上来,不方便。现在一般都用第二种了。

第二种只需要你在用户第一次登录的时候把一个默认的Locale存在session中就行了,然后用户在切换语言的时候同时更新session里的值,并且保存到数据库中,以便下次登录时用。

代码:

protected final Locale getSessionLocale(HttpServletRequest request) {
return (Locale) request.getSession().getAttribute(
SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
}
protected final void setSessionLocale(HttpServletRequest request,
Locale locale) {
request.getSession().setAttribute(
SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
}
protected final void setSessionLocale(HttpServletRequest request,
String code) {
request.getSession().setAttribute(
SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
new Locale(code.split("_")[0], code.split("_")[1]));
}

SessionLocaleResolver类是spring自带的,为的就是做国际化用。

code是语言代码,例如:zh_cn,zh_tw等等


取值方法:

protected final String getMessage(String key) {
ApplicationContext ac = WebApplicationContextUtils
.getRequiredWebApplicationContext(request.getSession()
.getServletContext());
return ac.getMessage(key, null, getSessionLocale(request));
}

key就是你的国际化字符串了,比如com.xxx.xxx.username

来自:求助得到的回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式