5.2.  JSF Web Pages - index.xhtml and create.xhtml

5.2.  JSF Web Pages - index.xhtml and create.xhtml

The index.xhtml file used is the same as in the EJB3/JSF example.

create.xhtml begins to reveal the difference that coding using the Seam framework makes.

<h:form id="create">

<f:facet name="beforeInvalidField">
  <h:graphicImage styleClass="errorImg" value="error.png"/>
</f:facet>
<f:facet name="afterInvalidField">
  <s:message styleClass="errorMsg" />
</f:facet>
<f:facet name="aroundInvalidField">
  <s:div styleClass="error"/>
</f:facet>

<s:validateAll>

<table>

  <tr>
    <td>Title:</td>
    <td>
      <s:decorate>
        <h:inputText id="title" value="#{todo.title}" size="15"/>
      </s:decorate>
    </td>
  </tr>

  <tr>
    <td>Description:</td>
    <td>
      <s:decorate>
        <h:inputTextarea id="description" value="#{todo.description}"/>
      </s:decorate>
    </td>
  </tr>

</table>

</s:validateAll>

<h:commandButton type="submit" id="create" value="Create"
                 action="#{todoDao.persist}"/>
</h:form>
		

The first thing that is different here is the Java Server Facelet code at the beginning, which works with the @NotNull validation constraint of our todo class to enforce and indicate invalid input to the user.

Also notice here that rather than requiring the use of a TodoBean class as we did in the EJB3/JSF example we back the form directly with a Todo entity bean. When this page is called, JSF asks Seam to resolve the variable todo due to JSF EL references such as #{todo.title}. Since there is no value already bound to that variable name, Seam will instantiate an entity bean of the todo class and return it to JSF, after storing it in the Seam context. The Seam context replaces the need for an intermediary bean.

The form input values are validated against the Hibernate Validator constraints specified in the todo class. JSF will redisplay the page if the constraints are violated, or it will bind the form input values to the Todo entity bean.

Entity beans shouldn't do database access or transaction management, so we can't use the Todo entity bean as a JSF action listener. Instead, creation of a new todo item in the database is accomplished by calling the persist method of a TodoDao session bean. When JSF requests Seam to resolve the variable todoDao through the JSF EL expression #{todoDao.persist}, Seam will either instantiate an object if one does not already exist, or else pass the existing stateful todoDao object from the Seam context. Seam will intercept the persist method call and inject the todo entity from the session context.

Let's have a look at the TodoDao class (defined in TodoDao.java) to see how this injection capability is implemented.