Discussions

Web tier: servlets, JSP, Web frameworks: [jsf] Backing bean vs custom component

  1. [jsf] Backing bean vs custom component (1 messages)

    I wonder what the general opinions are on implementing GUI behaviour in backing beans instead of custom components. As a small example, I have a panelgrid with a few commandlinks and images of flags in them that I would like to show some marker for the selected language.

    One aproach would be to let a backing bean discover the currently selected component and dynamically build a matching serie of column CSS classes. E.g.

    [code]
    <h:panelGrid columnClasses="#{lanCtrl.languageClasses}" binding="#{lanCtrl.languageGrid}" columns="2">
    <h:commandLink id="nl_NL" actionListener="#{lanCtrl.languageChange}" >
    <h:graphicImage url="images/dutch_flag_thumb.gif" />
    </h:commandLink>
    <h:commandLink id="en_US" actionListener="#{lanCtrl.languageChange}" >
    <h:graphicImage url="images/english_flag_thumb.gif" />
    </h:commandLink>
    </h:panelGrid>
    [/code]

    With the relevant parts in the backing bean being:

    [code]
    public void languageChange( ActionEvent event ) {
    UIComponent component = event.getComponent();
    locale = component.getId();
    }

    public String getLanguageClasses() {
    UIComponent selectedChild = grid.findComponent( locale );
    StringBuilder builder = new StringBuilder();
    for ( UIComponent child : (List<UIComponent>)grid.getChildren()) {
    if ( child == selectedChild ) {
    builder.append( "selected," );
    }
    else {
    builder.append( "notselected," );
    }
    }
    if (builder.length() > 1 ) {
    builder.deleteCharAt( builder.length()-1 );
    }
    return builder.toString();
    }
    [/code]

    The other possible aproach would be to create a custom component that tracks the selection of its own commandlink children. Surely this is not that difficult, but going down that road I'll probably end up with lots of different custom components for all those little GUI behaviours on every page.

    What would be the best approach?
  2. Have you atually considered if you could implement this logic in expression language directly - e.g. evaluating the locale in the style attribute, it might be simpler that having that all coded. However, that slight simplification apart I don't think that there is any problem with using expressions and a helper bean to do this.
    If you are to do a specific component do it in a nice generic way so it can be re-used elsewhere.