Best way to get TextProvider from ActionContext (i18n)

I adapted the code http://displaytag.svn.sourceforge.net/viewvc/displaytag/trunk/displaytag/src/main/java/org/displaytag/localization/I18nWebworkAdapter.java?revision=1173&view=markup that gets the i18n resource from key in Displaytag (see code below).

I was wondering if this is the cleanest approach (I don't like the iterator there). However, the only alternative I can see is to get the action from ActionInvocation (ActionContext.getContext (). GetActionInvocation (). GetAction ()) and rely on casting in ActionSupport to get the resource (which implements TextProvider). This does not seem very safe though (the action cannot extend the supportupport action).

Do you have any other suggestions?

/** * @see I18nResourceProvider#getResource(String, String, Tag, PageContext) */ public String getResource(String resourceKey, String defaultValue, Tag tag, PageContext pageContext) { // if resourceKey isn't defined either, use defaultValue String key = (resourceKey != null) ? resourceKey : defaultValue; String message = null; OgnlValueStack stack = TagUtils.getStack(pageContext); Iterator iterator = stack.getRoot().iterator(); while (iterator.hasNext()) { Object o = iterator.next(); if (o instanceof TextProvider) { TextProvider tp = (TextProvider) o; message = tp.getText(key, null, null); break; } } // if user explicitely added a titleKey we guess this is an error if (message == null && resourceKey != null) { log.debug(Messages.getString("Localization.missingkey", resourceKey)); //$NON-NLS-1$ message = UNDEFINED_KEY + resourceKey + UNDEFINED_KEY; } return message; } 
+4
source share
2 answers

The best way would be to do this in the same way as a text tag (implementation check), or the rest of the tags: by searching on the stack.

In addition, you probably do not want to explicitly point to ActionSupport , you will most likely want to check if it is valid for TextProvider , which really interests you.

I'm not sure your problem with the iterator is how it should be done, since your goal is to go through the stack and try with the highest TextProvider . You may not want to stop at the very top, depending on your needs / goals.

0
source

You can use the LocalizedTextUtil class to search for messages.

 LocalizedTextUtil.findDefaultText(key, ActionContext.getContext().getLocale()); 

This method accepts optional Object[] parameters, which are substituted in the message.

+4
source

All Articles