spring-webflow

What's the simplest way to define a transition that switches the locale and returns to the current view-state?


We do have the LocaleChangeInterceptor configured if that helps.

(Originally posted to http://forum.springsource.org/showthread.php?123391-Transition-to-set-locale )


Solution

  • This is not what I was seeking, but it's the only thing I found to do. That is, I created an action method to call from the transition:

        <transition on="switchLanguage" validate="false">
            <evaluate expression="myAction.switchLanguage"/>
        </transition>
    

    And, specifically in this case for an Action class that extends MultiAction:

    public Event switchLanguage(RequestContext context)
    {
        // get the "other" locale string itself from the current locale's resource bundle
        Locale locale = context.getExternalContext().getLocale();
        MessageSource ms = context.getActiveFlow().getApplicationContext();
        String newLocaleString = ms.getMessage("lang.other", null, locale);
    
        HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getNativeRequest();
        HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getNativeResponse();
    
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(req);
        localeResolver.setLocale(req, res, StringUtils.parseLocaleString(newLocaleString));
        return success();
    }
    

    Where, in my case, I only have to support two languages, so I define in my two messages.properties and messages_es.properties files, the property:

    lang.other=es
    

    or

    lang.other=en
    

    For other Action class approaches, return whatever you need to to indicate no failures, to either return to the same state again, or to transition to a new state, as desired.

    See https://docs.spring.io/spring-webflow/docs/2.5.1.RELEASE/reference/html/views.html#transition-actions

    If the transition action invokes a plain Java method, the invoked method may return a boolean whose value, true or false, indicates whether the transition should take place or be prevented from executing. A method may also return a String where the literal values "success", "yes", or "true" indicate the transition should occur, and any other value means the opposite.