如何在自定义的Struts 2 ActionMapper中设置区域设置 [英] How to set locale in a custom Struts 2 ActionMapper

查看:93
本文介绍了如何在自定义的Struts 2 ActionMapper中设置区域设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个自定义ActionMapper,它从URI(URI本身,而不是请求参数)中获取语言环境.在ActionMapper.getMapping()中,如何设置当前操作的语言环境?

I have implemented a custom ActionMapper which obtains the locale from the URI (the URI itself, not the request parameters). From within ActionMapper.getMapping(), how do I set the locale for the current action?

以下是我考虑过的一些想法:

Here are some ideas I've considered:

  • ActionContext.getCurrent().setLocale().不幸的是,似乎在调用该动作时会创建一个全新的ActionContext,并且语言环境已重置为默认值.
  • 设置参数request_locale,该参数将由i18n拦截器处理.不幸的是,i18n拦截器坚持不仅为当前操作而且为当前会话设置语言环境,这会引发异常,因为未为我的应用程序启用会话.
  • 通过实现setLocale()来设置参数并在操作本身中对其进行处理.简单明了,但这意味着没有一个拦截器可以访问该语言环境.
  • 设置一个参数并编写一个拦截器(基本上在不假设会话支持的情况下与i18n拦截器做同样的事情).对于这样一个简单的问题,似乎有点过头了,更不用说重新发明轮子了.

有没有简单的方法可以实现这一目标?

Is there any simple way of achieving this?

推荐答案

我确实确实最终设置了一个参数"locale",并使用它重写了i18n拦截器.

I did indeed end up setting a parameter "locale", and rewriting the i18n interceptor the use it.

从Struts 2.1.1开始,ActionMapping中的参数与请求参数保持分开. actionMappingParams拦截器采用这些参数,并将其应用于action对象.但是,我希望我的i18n拦截器使用"locale"参数,并且 not 不能将其传递给操作,这是我的操作方式:

Since Struts 2.1.1, parameters in the ActionMapping are kept separate from the request parameters. The actionMappingParams interceptor takes these parameters and applies them to the the action object. However, I wanted my i18n interceptor to consume the "locale" parameters and not pass it through to the action, Here's how I did it:

private static final String LOCALE_PARAMETER = "locale";

public String intercept(ActionInvocation invocation) throws Exception {
    ActionMapping mapping = (ActionMapping) invocation.getInvocationContext()
        .get(ServletActionContext.ACTION_MAPPING);
    Map params = mapping.getParams(); 
    Locale locale = (Locale) params.remove(LOCALE_PARAMETER);

    if(locale != null) {
        ActionContext.getContext().setLocale(locale);
    }

    return invocation.invoke();
}

此自定义i18n拦截器必须位于拦截器堆栈中的actionMappingParams之前.

This custom i18n interceptor must come before actionMappingParams in the interceptor stack.

这篇关于如何在自定义的Struts 2 ActionMapper中设置区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆