It's a Chameleon! About JSF Pages that change their appearance mid-flight (or: programmatic manipulation of JSF UI Components)

11

One of the features in Java Server Faces that distinguishes it from for example JSP technology, is the ability to access UI Components programmatically, at run-time. This makes it possible not only to inspect the state of these components, but also to manipulate them. One advanced type of manipulation is the run-time creation of new components: reading some kind of meta-data that describes the components that are desired, our application can extend pages while the application is running (and only for the current session context). Our pages now consist of part static definitions, created using JSF JSP tags in JSP pages and part dynamically added or modified components.

In this article I will demonstrate how such manipulation can be implemented. The case here is a prototype for an Evaluation Application for our technische sessions. The session coordinator can predefine the questions he wants to put to the attendants. Based on these question-definitions, each session attendant will be presented with a web-page with all the questions and (multiple choice) answer options. This same approach can be used for Quiz and on Line Exam applications. The JSF implementation used is the standard JSR (Sun) Reference Implementation (1.1).

 

....

With a simple JSF JSP page, I create a UI where a Poll Question can be defined. The question text is entered in an InputText. Then we can specify whether the question requires an Open Answer – free text as typed by the user -, a single selection from a predefined set of multiple options or possibly multiple selections from that set of options. Next we can pick the widget to use for this question. Note: this is only relevant if the Answer Style is not Open Answer! We can choose between a tick-in-the-box widget (checkbox or radio button, depending on whether it is a single or multiple answer), a list or a menu style item.

The item Answer Options is where we define the various options that the user may pick his answers from. This is done in the format:

value,label<br />value,label<br />

 

If we click the Rephrase Question button, we see the display of the question and allowable answers that we specified.

 

The JSF code that defines this page is fairly simple. The most important part probably is the part we cannot see in the screenprint above:

...<br />      &lt;body style=&quot;font-family:sans-serif&quot; &gt;&lt;h:form id=&quot;form1&quot;&gt;<br />          &lt;h:outputText value=&quot;Poll Picker - Compose a Poll Question&quot;<br />                        id=&quot;outputText1&quot;<br />                        style=&quot;font-family:sans-serif; font-size:x-large; font-weight:bolder; text-decoration:underline;&quot;/&gt;<br />          &lt;h:panelGrid columns=&quot;2&quot; binding=&quot;#{pollPickerBacker.panelGrid1}&quot;<br />                       id=&quot;panelGrid1&quot;&gt;<br />            &lt;h:outputLabel value=&quot;Question&quot;<br />                           id=&quot;outputLabel2&quot; for=&quot;question&quot;/&gt;<br />            &lt;h:inputText id=&quot;question&quot;<br />                         title=&quot;Type the question text that will be presented to the user&quot;<br />                         size=&quot;80&quot; value=&quot;#{pollPickerBacker.question}&quot;/&gt;<br />            &lt;h:outputLabel value=&quot;Answer Style&quot;<br />                           id=&quot;outputLabel1&quot;<br />                           title=&quot;Indicate the number of answers that can be given to the question&quot;<br />                           for=&quot;answerStyle&quot;/&gt;<br />            &lt;h:selectOneRadio value=&quot;#{pollPickerBacker.answerStyle}&quot;<br />                              id=&quot;answerStyle&quot;&gt;<br />              &lt;f:selectItem itemLabel=&quot;Open Answer&quot; itemValue=&quot;o&quot;<br />                            id=&quot;selectItem0&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;Single Answer&quot; itemValue=&quot;s&quot;<br />                            id=&quot;selectItem1&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;Multiple Answers&quot; itemValue=&quot;m&quot;<br />                            id=&quot;selectItem2&quot;/&gt;<br />            &lt;/h:selectOneRadio&gt;<br />            &lt;h:outputLabel value=&quot;Widget style&quot;<br />                           id=&quot;outputLabel3&quot;<br />                           title=&quot;Note: not relevant when Open Answer is selected&quot;/&gt;<br />            &lt;h:selectOneRadio value=&quot;#{pollPickerBacker.widgetStyle}&quot;<br />                              id=&quot;widgetStyle&quot;&gt;<br />              &lt;f:selectItem itemLabel=&quot;Radio/Check&quot; itemValue=&quot;tick&quot;<br />                            id=&quot;selectItem3&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;List&quot; itemValue=&quot;list&quot;<br />                            id=&quot;selectItem4&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;Menu&quot; itemValue=&quot;menu&quot;<br />                            id=&quot;selectItem5&quot;/&gt;<br />            &lt;/h:selectOneRadio&gt;<br />            &lt;h:outputLabel value=&quot;Answer options&quot;<br />                           id=&quot;outputLabel4&quot;/&gt;<br />            &lt;h:inputTextarea id=&quot;inputTextarea1&quot; cols=&quot;40&quot; rows=&quot;5&quot;<br />                             value=&quot;#{pollPickerBacker.answerOptions}&quot;/&gt;<br />            &lt;h:commandButton value=&quot;Rephrase Question&quot;<br />                             id=&quot;commandButton1&quot; type=&quot;submit&quot;<br />                             action=&quot;#{pollPickerBacker.rephraseQuestionAction}&quot;/&gt;<br />          &lt;/h:panelGrid&gt;<br />          &lt;hr/&gt;<br />          &lt;h:outputText value=&quot;Could you please answer the following question:&quot;<br />                        id=&quot;outputText2&quot;<br />                        style=&quot;font-family:sans-serif; font-size:x-large; font-weight:bolder; text-decoration:underline;&quot;/&gt;<br />          &lt;p&gt;<br />            &lt;h:messages/&gt;&lt;h:panelGrid binding=&quot;#{pollPickerBacker.questionPanel}&quot;<br />                                      id=&quot;questionPanel&quot; columns=&quot;2&quot;/&gt;<br />          &lt;/p&gt;<br />        &lt;/h:form&gt;&lt;/body&gt;<br />    &lt;/html&gt;<br />  &lt;/f:view&gt;<br />&lt;/jsp:root&gt;<br />&nbsp;

That most important definition is the PanelGrid underneath the heading "Could you please answer the following question:". This component has a binding defined: binding="#{pollPickerBacker.questionPanel}". This makes the PanelGrid accessible in the pollPickerBacker bean which in turns allows us to add newly created UI Components to it. Note: we could also have used FacesContext.getCurrentInstance().getViewRoot().findComponent() to get hold of this component instead of using the binding property. 

The Backing Bean 

The Backing Bean not only holds the values for Question, AnswerStyle, WidgetStyle and AnswerOptions, it also binds the panelGrid and implements the ActionListener method activated by the CommandButton rephrase question. The method rephraseQuestionAction on this bean is where all the action is:

    public String rephraseQuestionAction() {<br />        Application application = <br />            FacesContext.getCurrentInstance().getApplication();<br />        List children = getQuestionPanel().getChildren();<br />        children.clear();<br />        // create ques
tion text<br />         HtmlOutput
Label questionPrompt = <br />             (HtmlOutputLabel)application.createComponent(HtmlOutputLabel.COMPONENT_TYPE);<br />        questionPrompt.setValue(&quot;Question:&quot;);             <br />        HtmlOutputText question = <br />            (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);<br />        question.setValue(getQuestion());<br />        HtmlOutputLabel answerPrompt = <br />            (HtmlOutputLabel)application.createComponent(HtmlOutputLabel.COMPONENT_TYPE);<br />        answerPrompt.setValue(&quot;Answer:&quot;);<br />        children.add(questionPrompt);<br />        children.add(question);<br />        children.add(answerPrompt);<br />        // create answer elements (either InputText or a SelectOne or SelectMany)<br />        UIComponent answer = null;<br />        ValueBinding answerBinding = null;<br />        if (&quot;o&quot;.equalsIgnoreCase(getAnswerStyle())) {<br />            answer =  (HtmlInputText)application.createComponent(HtmlInputText.COMPONENT_TYPE);<br />            LengthValidator lengthValidator = <br />                (LengthValidator)application.createValidator(LengthValidator.VALIDATOR_ID);<br />            lengthValidator.setMinimum(2); // an answer must have at least two characters<br />            lengthValidator.setMaximum(200); // an answer must be no longer than 200 characters<br />            ((HtmlInputText)answer).addValidator(lengthValidator);<br />            // bind the value property to the answer property in the pollPickerBacker bean<br />            answerBinding = application.createValueBinding(&quot;#{pollPickerBacker.answer}&quot;);             <br />        } else {<br />            if (&quot;s&quot;.equalsIgnoreCase(getAnswerStyle())) {<br />                if (&quot;tick&quot;.equalsIgnoreCase(getWidgetStyle())) {<br />                  answer = (HtmlSelectOneRadio)application.createComponent(HtmlSelectOneRadio.COMPONENT_TYPE);<br />                }<br />                if (&quot;list&quot;.equalsIgnoreCase(getWidgetStyle())) {<br />                  answer = (HtmlSelectOneListbox)application.createComponent(HtmlSelectOneListbox.COMPONENT_TYPE);<br />                }<br />                if (&quot;menu&quot;.equalsIgnoreCase(getWidgetStyle())) {<br />                  answer = (HtmlSelectOneMenu)application.createComponent(HtmlSelectOneMenu.COMPONENT_TYPE);<br />                }<br />              answerBinding = application.createValueBinding(&quot;#{pollPickerBacker.answer}&quot;);             <br />            } else if (&quot;m&quot;.equalsIgnoreCase(getAnswerStyle())) {<br />                if (&quot;tick&quot;.equalsIgnoreCase(getWidgetStyle())) {<br />                    answer = (HtmlSelectManyCheckbox)application.createComponent(HtmlSelectManyCheckbox.COMPONENT_TYPE);<br />                }<br />                if (&quot;list&quot;.equalsIgnoreCase(getWidgetStyle())) {<br />                  answer = (HtmlSelectManyListbox)application.createComponent(HtmlSelectManyListbox.COMPONENT_TYPE);<br />                }<br />                if (&quot;menu&quot;.equalsIgnoreCase(getWidgetStyle())) {<br />                  answer = (HtmlSelectManyMenu)application.createComponent(HtmlSelectManyMenu.COMPONENT_TYPE);<br />                }<br />                answerBinding = application.createValueBinding(&quot;#{pollPickerBacker.answers}&quot;);             <br />            }<br />            answer.getChildren().add(getAnswerOptionItems());<br />        }<br />        answer.setId(&quot;answer&quot;);<br />       <br />        answer.setValueBinding(&quot;value&quot;, answerBinding);<br />        children.add(answer);<br /><br />        HtmlCommandButton submitButton = <br />            (HtmlCommandButton)application.createComponent(HtmlCommandButton.COMPONENT_TYPE);<br />        submitButton.setValue(&quot;Post your answer&quot;);<br /><br />        children.add(submitButton);<br />        return null;<br />    } <br />

 

Note how we create a new ValueBinding for the expression #{pollPickerBacker.answers} for multiple answers and #{pollPickerBacker.answer} for singular answers. These bindings ensure that any value entered by the user in the answer item – being it an InputText or a RadioGroup or a List – is stored on the answer or answers property of the backing bean (and is also read from that property’s getter method when the page is rendered).

If we now for example change the question definition:

 

And click on the Rephrase Question button, the rephraseQuestionAction clears the PanelGrid, creates three OutputLabels – two for prompts, one for the question text- and adds either an InputText for an open answer, a radiogroup or select for a single answer or a set of checkboxes or a list for multiple answers:

 

Below you find the code of the utility method that takes the Answer Options textarea’s content and parses it into a UISelectItems component:

    private UISelectItems getAnswerOptionItems() {<br />        Application application = <br />            FacesContext.getCurrentInstance().getViewRoot().findComponent();<br />            <br />        UISelectItems selectItems = <br />            (UISelectItems)application.createComponent(UISelectItems.COMPONENT_TYPE);<br />        ArrayList options = new ArrayList();    <br />        // split answerOptions on Carriage Return into label,value pairs<br />        StringTokenizer st = new StringTokenizer (getAnswerOptions());<br />        while (st.hasMoreTokens ()) {<br />          // split every row into label and key<br />          StringTokenizer st2 = new StringTokenizer (st.nextToken(),&quot;,&quot;);<br />          options.add(new SelectItem(st2.nextToken(), st2.nextToken()));<br />          }             <br />        selectItems.setValue(options);<br />        return selectItems;<br />    }<br />&nbsp;

The importance of this functionality to manipulate the pages in our own code lies largely in the options open to us to adopt an application to user preferences and even more interestingly: to drive part of our application from run-time meta-data. In this example, the user provides the meta-data inside the application. However, it seems more meaningful to have an application administrator or even a developer define such meta-data in some sort of maintenance application and use a more extended version of our backingbean in this code example as pre-render processor.

 

Resources

I am still a happy reader and user of Java Server Faces in Action by Kito Mann (Manning Publishing).

The sources for this article can be downloaded as JDeveloper 10.1.3 Application. Note that the sources can be used in any IDE, if you configure a project yourself: Chameleon.zip.

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

11 Comments

  1. REALLY useful!
    I used your techniques to build a page/bean combo that dynamically displays any table in a database, using <h:dataTable>, generated based on the table’s database metadata – sure beats one page per table!

  2. In reply to my own comment, I have found that the best point to access the UIPanelGrid is in the setter from the binding. ie, if you have:
    then in Bean.java you can have: setThePanel( UIPanel panel) { this.panel = panel; augmentPanel(); }
    The panel that is passed in has nothing constructed on it and its id attribute is null, but you can still programmatically add components to it for it to render correctly.
    In addition to this, if you have components added in the JSP also, they are preserved and merged with your programmatic additions.
    Quite cool, really.
    Regards,
    Stewart

  3. Hi Lucas,
    This is an excellent article, and I thank you for writing it.

    One curious situation I have, which I have been unable to solve, is that of programmatically creating the initial page.
    I have tried various ways of accessing the created components, such as through a bean or PhaseListener.
    It appears the page is not constructed at any point up to and including before RENDER_RESPONSE;
    however, if I try programmatic manipulation after RENDER_RESPONSE, apparently the page has already been written to the browser,
    so it’s there on a refresh, but not that first time.

    Anyone have any ideas?

    Thanks,

    Stewart

  4. Lucas, Could you please expand on what happens after one hits ‘Post your answer’? I am asking because while I am doing something similar and have been able to the ‘value’ of the selectItem but have not been able to successfully utilize getItemLabel. If you needed to access the label portion of the item selected as an ‘Answer’, how would you do it? Thanks, Jeanne

  5. I was thinking about a printable version or a pdf dowload of the article. I will copy and paste the content of the article. Thanks.

  6. Giuseppe, I am not entirely sure what you mean. All content is right there on the weblog. I have no Word document to back it up. You can just copy and paste it from the site – same as I would to provide this printable copy (at least if a Word document or something similar is what you are after). Is there anything in particular I can do for you?

  7. Lucas, nice article as previous that I have seen in this blog. Is it possible to have a printable version of this article? Thanks in advance. Giuseppe

  8. Dmitry,
    In this specific example, that would work. However, as I suggest in the article, there may be cases – especially when setting up a questionnaire style application – where the meta-data specifying the page’s look & feel are more maintained in a database and are much more voluminous and contain much more complicated – in part dynamically created – page fragment definitionis. It would be much harder to proactively anticipate al possible pieces of page elements (and their relative sequencing) in a JSP.

    I agree that whenever a JSP can get you there with relatively simple (JSTL and EL) logic, it is preferable to defining the UI Components in code. But as soon as the JSP starts to grow fat with lots of if-conditions and repetitions of the same component definitions, resorting to code based run-time manipulation to me is certainly a valuable option.

    By the way, how many lines of Servlet code would you need to achieve what this snippet of code does:

    UIComponent answer = (HtmlSelectOneRadio)application.createComponent(HtmlSelectOneRadio.COMPONENT_TYPE);
    ValueBinding answerBinding = application.createValueBinding(“#{pollPickerBacker.answer}”);
    answer.getChildren().add(getAnswerOptionItems());
    answer.setId(“answer”);
    answer.setValueBinding(“value”, answerBinding);
    children.add(answer);

    You cannot make that comparison with out.println() too lightly: we are talking 7 lines of code vs. a very substantial number – in the Servlet approach you need to take care of so many things the UI Components in particular and JSF in general does for you.

  9. So, depending on the choice we need to render the different views. And view in this example is actually generated in our Java code. Like old servlets: out.println(…)
    Sure it will work, but I prefer to keep code for controls in JSP. It is just much more easy to update. So this condition could be checked in JSP for example:

    if (“s”.equalsIgnoreCase(getAnswerStyle()))

    Dmitry
    http://www.servletsuite.com/