How to set locale in a custom Struts 2 ActionMapper

元气小坏坏 提交于 2019-12-31 05:08:05

问题


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(). Unfortunately, it seems that a fresh new ActionContext is created when the action is invoked, and the locale is reset to the default.
  • Set the parameter request_locale, which will be processed by the i18n interceptor. Unfortunately, the i18n interceptor insists on setting the locale for not just the current action but the current session too, which throws an exception because sessions are not enabled for my application.
  • Set a parameter and process it in the action itself, by implementing setLocale(). Straightforward, but it means that none of the interceptors will have access to the locale.
  • Set a parameter and write an interceptor (to basically do the same thing as the i18n interceptor without assuming session support). Seems like overkill for such a simple issue, not to mention re-inventing the wheel.

Is there any simple way of achieving this?


回答1:


you can use the provided I18nInterceptor when you set the param: request_only_locale

instead of request_locale

request_only_locale stores the locale only for the requests and does not touch the Session.

Cheers, Christian




回答2:


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

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();
}

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



来源:https://stackoverflow.com/questions/1292981/how-to-set-locale-in-a-custom-struts-2-actionmapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!