views:

2063

answers:

1

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?

A: 

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.

Todd Owen