How to set locale in a custom Struts 2 ActionMapper

前端 未结 2 703
悲哀的现实
悲哀的现实 2021-01-26 10:49

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

相关标签:
2条回答
  • 2021-01-26 11:18

    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.

    0 讨论(0)
  • 2021-01-26 11:28

    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

    0 讨论(0)
提交回复
热议问题