获取操作类中 i18n 拦截器检测到的用户语言环境

2022-01-16 00:00:00 internationalization java struts2

我有一个使用 Struts 2 的 webapp.我使用 i18n 拦截器和所有默认设置.我认为这个拦截器的工作原理如下:

I have a webapp that uses Struts 2. I use the i18n interceptor with all the default settings. I thought this interceptor worked as follow:

  1. 如果有参数request_locale,去掉这个参数,将此语言环境放在会话中以供将来使用.
  2. 如果没有参数,则在 httpheader 中搜索语言环境并将其放置会话中的语言环境以供将来使用.

所以在我的动作类(实现 sessionAware)中,我有以下方法:

So in my action class (which implements sessionAware) I have the following method:

public String getUserLocale()
{
    return (String) session.get("WW_TRANS_I18N_LOCALE");
}

但是,这种方法在情况 #2 中不起作用,它只是返回 null.所以我的问题是:如果没有明确的请求参数,我如何让我的操作知道 i18n 拦截器检测到的用户语言环境?因为它没有存储在会话中?

However, this method does not work in situation #2, it just returns null. So my question is: how can I let my action know the user locale that the i18n interceptor detected if there is no explicit request parameter? Because it is not stored in the session?

推荐答案

您不应该使用由拦截器定义的会话密钥供内部使用来获取操作区域设置.

You shouldn't use a session key defined by the interceptor for internal usage to get an action locale.

如果 i18n 拦截器检测到 request_locale 参数,则创建请求的语言环境并将其放入操作上下文以及拦截器指定的键下的会话.

If a request_locale parameter is detected by the i18n interceptor the requested locale is created and put to the action context and also to the session under the key specified by the interceptor.

如果对拦截器的下一个请求不包含 request_locale 参数,则它会获取保存在会话中的区域设置,如果未找到则使用请求区域设置.

If the next request to the interceptor doesn't include request_locale parameter then it gets a locale saved in the session, if not found the request locale is used.

拦截器再次将返回的语言环境放入操作上下文.因此,要获得 struts 标签使用的语言环境,您应该使用

Again the interceptor put returned locale to the action context. So, to get a locale used by the struts tags you should use

 Locale locale = ActionContext.getContext().getLocale(); 

相关文章