Todd Owen
Todd Owen

Reputation: 16208

How to set locale in a custom Struts 2 ActionMapper

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:

Is there any simple way of achieving this?

Upvotes: 0

Views: 11065

Answers (2)

Christian
Christian

Reputation: 7141

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

Upvotes: 1

Todd Owen
Todd Owen

Reputation: 16208

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.

Upvotes: 0

Related Questions