SeamFramework.org Community Documentation

- Prev
- Next

## Chapter 34. Seam JSF controls

Seam includes a number of JSF controls that are useful for working with Seam. These are intended to complement the built-in JSF controls, and controls from other third-party libraries. We recommend JBoss RichFaces, ICEsoft ICEfaces and Apache MyFaces Trinidad tag libraries for use with Seam. We do not recommend the use of the Tomahawk tag library.

## 34.1. Tags

To use these tags, define the "`s`" namespace in your page as follows (facelets only):

    <html xmlns="http://www.w3.org/1999/xhtml"

          xmlns:s="http://jboss.org/schema/seam/taglib">

The ui example demonstrates the use of a number of these tags.

### 34.1.1. Navigation Controls

#### 34.1.1.1. `<s:button>`

Description

A button that supports invocation of an action with control over conversation propagation. Does not submit the form.

Attributes

- `value` — the label.

- `action` — a method binding that specified the action listener.

- `view` — the JSF view id to link to.

- `fragment` — the fragment identifier to link to.

- `disabled` — is the link disabled?

- `propagation` — determines the conversation propagation style: `begin`, `join`, `nested`, `none`, `end` or `endRoot`.

- `pageflow` — a pageflow definition to begin. (This is only useful when `propagation="begin"` or `propagation="join"` is used).

- `includePageParams` — when set to false, page parameters defined in `pages.xml` will be excluded from rendering.

Usage

    <s:button id="cancel"

              value="Cancel"

              action="#{hotelBooking.cancel}"/>

You can specify both `view` and `action` on `<s:link />`. In this case, the action will be called once the redirect to the specified view has occurred.

The use of action listeners (including the default JSF action listener) is not supported with `<s:button />`.

#### 34.1.1.2. `<s:conversationId>`

Description

Add the conversation id to JSF link or button (e.g. `<h:commandLink />` , `<s:button />`).

Attributes

None

#### 34.1.1.3. `<s:taskId>`

Description

Add the task id to an output link (or similar JSF control), when the task is available via `#{task}`.

Attributes

None.

#### 34.1.1.4. `<s:link>`

Description

A link that supports invocation of an action with control over conversation propagation. Does not submit the form.

The use of action listeners (including the default JSF action listener) is not supported with `<s:link />`.

Attributes

- `value` — the label.

- `action` — a method binding that specified the action listener.

- `view` — the JSF view id to link to.

- `fragment` — the fragment identifier to link to.

- `disabled` — is the link disabled?

- `propagation` — determines the conversation propagation style: `begin`, `join`, `nested`, `none`, `end` or `endRoot`.

- `pageflow` — a pageflow definition to begin. (This is only useful when using `propagation="begin"` or `propagation="join"`.)

- `includePageParams` — when set to false, page parameters defined in `pages.xml` will be excluded from rendering.

Usage

    <s:link id="register" view="/register.xhtml"

            value="Register New User"/>

You can specify both `view` and `action` on `<s:link />`. In this case, the action will be called once the redirect to the specified view has occured.

#### 34.1.1.5. `<s:conversationPropagation>`

Description

Customize the conversation propagation for a command link or button (or similar JSF control). Facelets only.

Attributes

- `type` — determines the conversation propagation style: `begin`, `join`, `nested`, `none`, `end` or `endRoot`.

- `pageflow` — a pageflow definition to begin. (This is only useful when using `propagation="begin"` or `propagation="join"`.)

Usage

    <h:commandButton value="Apply" action="#{personHome.update}">

       <s:conversationPropagation type="join" />

    </h:commandButton>

#### 34.1.1.6. `<s:defaultAction>`

Description

Specify the default action to run when the form is submitted using the enter key.

Currently you can only nest it inside buttons (e.g. `<h:commandButton />`, `<a:commandButton />` or `<tr:commandButton />`).

You must specify an id on the action source. You can only have one default action per form.

Attributes

None.

Usage

    <h:commandButton id="foo" value="Foo" action="#{manager.foo}">

       <s:defaultAction />

    </h:commandButton>

### 34.1.2. Converters and Validators

#### 34.1.2.1. `<s:convertDateTime>`

Description

Perform date or time conversions in the Seam timezone.

Attributes

None.

Usage

    <h:outputText value="#{item.orderDate}">

       <s:convertDateTime type="both" dateStyle="full"/>

    </h:outputText>

#### 34.1.2.2. `<s:convertEntity>`

Description

Assigns an entity converter to the current component. This is useful for radio button and dropdown controls.

The converter works with any managed entity - either simple or composite. The converter should be able to find the items declared in the JSF controls on form submission, otherwise you will receive a validation error.

Attributes

None.

Configuration

You must use Seam managed transactions (see Section 10.2, “Seam managed transactions”) with `<s:convertEntity />`.

If your Managed Persistence Context isn't called `entityManager`, then you need to set it in components.xml:

    <components xmlns="http://jboss.org/schema/seam/components"
                xmlns:ui="http://jboss.org/schema/seam/ui">

       <ui:jpa-entity-loader entity-manager="#{em}" />

If you are using a Managed Hibernate Session then you need to set it in components.xml:

    <components xmlns="http://jboss.org/schema/seam/components"
                xmlns:ui="http://jboss.org/schema/seam/ui">

       <ui:hibernate-entity-loader />

If your Managed Hibernate Session isn't called `session`, then you need to set it in components.xml:

    <components xmlns="http://jboss.org/schema/seam/components"
                xmlns:ui="http://jboss.org/schema/seam/ui">

       <ui:hibernate-entity-loader session="#{hibernateSession}" />

If you want to use more than one entity manager with the entity converter, you can create a copy of the entity converter for each entity manager in `components.xml` - note how the entity converter delegates to the entity loader to perform persistence operations:

    <components xmlns="http://jboss.org/schema/seam/components"
                xmlns:ui="http://jboss.org/schema/seam/ui">

       <ui:entity-converter name="standardEntityConverter" entity-loader="#{standardEntityLoader}" />

       <ui:jpa-entity-loader name="standardEntityLoader" entity-manager="#{standardEntityManager}" />

       <ui:entity-converter name="restrictedEntityConverter" entity-loader="#{restrictedEntityLoader}" />

       <ui:jpa-entity-loader name="restrictedEntityLoader" entity-manager="#{restrictedEntityManager}" />

    <h:selectOneMenu value="#{person.continent}">
       <s:selectItems value="#{continents.resultList}" var="continent"
                      label="#{continent.name}" />
        <f:converter converterId="standardEntityConverter" />
    </h:selectOneMenu>

Usage

    <h:selectOneMenu value="#{person.continent}" required="true">

       <s:selectItems value="#{continents.resultList}" var="continent"

                      label="#{continent.name}"

                      noSelectionLabel="Please Select..."/>

       <s:convertEntity />

    </h:selectOneMenu>

#### 34.1.2.3. `<s:convertEnum>`

Description

Assigns an enum converter to the current component. This is primarily useful for radio button and dropdown controls.

Attributes

None.

Usage

    <h:selectOneMenu value="#{person.honorific}">

       <s:selectItems value="#{honorifics}" var="honorific"

                     label="#{honorific.label}"

                     noSelectionLabel="Please select" />

       <s:convertEnum />

    </h:selectOneMenu>

#### 34.1.2.4. `<s:convertAtomicBoolean>`

Description

`javax.faces.convert.Converter` for `java.util.concurrent.atomic.AtomicBoolean`.

Attributes

None.

Usage

    <h:outputText value="#{item.valid}">
       <s:convertAtomicBoolean />
    </h:outputText>

#### 34.1.2.5. `<s:convertAtomicInteger>`

Description

`javax.faces.convert.Converter` for `java.util.concurrent.atomic.AtomicInteger`.

Attributes

None.

Usage

    <h:outputText value="#{item.id}">
       <s:convertAtomicInteger />
    </h:outputText>

#### 34.1.2.6. `<s:convertAtomicLong>`

Description

`javax.faces.convert.Converter` for `java.util.concurrent.atomic.AtomicLong`.

Attributes

None.

Usage

    <h:outputText value="#{item.id}">
       <s:convertAtomicLong />
    </h:outputText>

#### 34.1.2.7. `<s:validateEquality>`

Description

Tag to nest inside an input control to validate that its parent's value is equal (or not equal!) to the referenced control's value.

Attributes

- `for` — The id of a control to validate against.

- `message` — Message to show on failure.

- `required` — False will disable a check that a value at all is inputted in fields.

- `messageId` — Message id to show on failure.

- `operator` — What operator to use when comparing the values Valid operators are:

  - `equal` — Validates that value.equals(forValue)

  - `not_equal` — Validates that !value.equals(forValue)

  - `greater` — Validates that ((Comparable)value).compareTo(forValue) > 0

  - `greater_or_equal` — Validates that ((Comparable)value).compareTo(forValue) >= 0

  - `less` — Validates that ((Comparable)value).compareTo(forValue) < 0

  - `less_or_equal` — Validates that ((Comparable)value).compareTo(forValue) <= 0

Usage

    <h:inputText id="name" value="#{bean.name}"/>
    <h:inputText id="nameVerification" >
       <s:validateEquality for="name" />
    </h:inputText>

#### 34.1.2.8. `<s:validate>`

Description

A non-visual control, validates a JSF input field against the bound property using Hibernate Validator.

Attributes

None.

Usage

    <h:inputText id="userName" required="true"

                 value="#{customer.userName}">

      <s:validate />

    </h:inputText>

    <h:message for="userName" styleClass="error" />

#### 34.1.2.9. `<s:validateAll>`

Description

A non-visual control, validates all child JSF input fields against their bound properties using Hibernate Validator.

Attributes

None.

Usage

    <s:validateAll>

      <div class="entry">

        <h:outputLabel for="username">Username:</h:outputLabel>

        <h:inputText id="username" value="#{user.username}"

                     required="true"/>

        <h:message for="username" styleClass="error" />

      </div>

      <div class="entry">

        <h:outputLabel for="password">Password:</h:outputLabel>

        <h:inputSecret id="password" value="#{user.password}"

                       required="true"/>

        <h:message for="password" styleClass="error" />

      </div>

      <div class="entry">

        <h:outputLabel for="verify">Verify Password:</h:outputLabel>

        <h:inputSecret id="verify" value="#{register.verify}"

                       required="true"/>

        <h:message for="verify" styleClass="error" />

      </div>

    </s:validateAll>

### 34.1.3. Formatting

#### 34.1.3.1. `<s:decorate>`

Description

"Decorate" a JSF input field when validation fails or when `required="true"` is set.

Attributes

- `template` — the facelets template to use to decorate the component

- `enclose` — if true, the template used to decorate the input field is enclosed by the element specified with the "element" attribute. By default this is a div element.

- `element` — the element to enclose the template used to decorate the input field. By default, the template is enclosed with a div element.

`#{invalid}` and `#{required}` are available inside `s:decorate`; `#{required}` evaluates to `true` if you have set the input component being decorated as required, and `#{invalid}` evaluates to `true` if a validation error occurs.

Usage

    <s:decorate template="edit.xhtml">

       <ui:define name="label">Country:</ui:define>

          <h:inputText value="#{location.country}" required="true"/>

       </s:decorate>

    <ui:composition xmlns="http://www.w3.org/1999/xhtml"

       xmlns:ui="http://java.sun.com/jsf/facelets"

       xmlns:h="http://java.sun.com/jsf/html"

       xmlns:f="http://java.sun.com/jsf/core"

       xmlns:s="http://jboss.org/schema/seam/taglib">

       <div>

          <s:label styleClass="#{invalid?'error':''}">

             <ui:insert name="label"/>

             <s:span styleClass="required" rendered="#{required}">*</s:span>

          </s:label>

          <span class="#{invalid?'error':''}">

             <s:validateAll>

                <ui:insert/>

             </s:validateAll>

          </span>

          <s:message styleClass="error"/>

       </div>

    </ui:composition>

#### 34.1.3.2. `<s:div>`

Description

Render a HTML `<div>`.

Attributes

None.

Usage

    <s:div rendered="#{selectedMember == null}">

       Sorry, but this member does not exist.

    </s:div>

#### 34.1.3.3. `<s:span>`

Description

Render a HTML `<span>`.

Attributes

- `title` — Title for a span.

Usage

    <s:span styleClass="required" rendered="#{required}" title="Small tooltip">*</s:span>

#### 34.1.3.4. `<s:fragment>`

Description

A non-rendering component useful for enabling/disabling rendering of it's children.

Attributes

None.

Usage

    <s:fragment rendered="#{auction.highBidder ne null}">

       Current bid:

    </s:fragment>

#### 34.1.3.5. `<s:label>`

Description

"Decorate" a JSF input field with the label. The label is placed inside the HTML `<label>` tag, and is associated with the nearest JSF input component. It is often used with `<s:decorate>`.

Attributes

- `style` — The control's style

- `styleClass` — The control's style class

Usage

    <s:label styleClass="label">

      Country:

    </s:label>

    <h:inputText value="#{location.country}" required="true"/>

#### 34.1.3.6. `<s:message>`

Description

"Decorate" a JSF input field with the validation error message.

Attributes

None.

Usage

    <f:facet name="afterInvalidField">

      <s:span>

        &#160;Error:&#160;

        <s:message/>

      </s:span>

    </f:facet>

### 34.1.4. Seam Text

#### 34.1.4.1. `<s:formattedText>`

Description

Outputs Seam Text, a rich text markup useful for blogs, wikis and other applications that might use rich text. See the Seam Text chapter for full usage.

Attributes

- `value` — an EL expression specifying the rich text markup to render.

Usage

    <s:formattedText value="#{blog.text}"/>

Example

### 34.1.5. Form support

#### 34.1.5.1. `<s:token>`

Description

Produces a random token that is inserted into a hidden form field to help to secure JSF form posts against cross-site request forgery (XSRF) attacks. Note that the browser must have cookies enabled to submit forms that include this component.

Attributes

- `requireSession` — indicates whether the session id should be included in the form signature, hence binding the token to the session. This value can be set to false if the "build before restore" mode of Facelets is activated (the default in JSF 2.0). (default: false)

- `enableCookieNotice` — indicates that a JavaScript check should be inserted into the page to verify that cookies are enabled in the browser. If cookies are not enabled, present a notice to the user that form posts will not work. (default: false)

- `allowMultiplePosts` — indicates whether to allow the same form to be submitted multiple times with the same signature (as long as the view does not change). This is a common need if the form is perform Ajax calls but not rerendering itself or, at the very least, the UIToken component. The preferred approach is to have the UIToken component rerendered on any Ajax call where the UIToken component would be processed. (default: false)

Usage

    <h:form>

       <s:token enableCookieNotice="true" requireSession="false"/>

       ...

    </h:form>

#### 34.1.5.2. `<s:enumItem>`

Description

Creates a `SelectItem` from an enum value.

Attributes

- `enumValue` — the string representation of the enum value.

- `label` — the label to be used when rendering the `SelectItem`.

Usage

    <h:selectOneRadio id="radioList"

                      layout="lineDirection"

                      value="#{newPayment.paymentFrequency}">

       <!-- JSF 2 way <f:converter converterId="org.jboss.seam.ui.EnumConverter" />-->

       <s:convertEnum />

       <s:enumItem enumValue="ONCE"         label="Only Once" />

       <s:enumItem enumValue="EVERY_MINUTE" label="Every Minute" />

       <s:enumItem enumValue="HOURLY"       label="Every Hour" />

       <s:enumItem enumValue="DAILY"        label="Every Day" />

       <s:enumItem enumValue="WEEKLY"       label="Every Week" />

    </h:selectOneRadio>

#### 34.1.5.3. `<s:selectItems>`

Description

Creates a `List<SelectItem>` from a List, Set, DataModel or Array.

Attributes

- `value` — an EL expression specifying the data that backs the `List<SelectItem>`

- `var`— defines the name of the local variable that holds the current object during iteration

- `label` — the label to be used when rendering the `SelectItem`. Can reference the `var` variable.

- `itemValue` — Value to return to the server if this option is selected. Optional, by default the `var` object is used. Can reference the `var` variable.

- `disabled` — if true the `SelectItem` will be rendered disabled. Can reference the `var` variable.

- `noSelectionLabel` — specifies the (optional) label to place at the top of list (if `required="true"` is also specified then selecting this value will cause a validation error).

- `hideNoSelectionLabel` — if true, the `noSelectionLabel` will be hidden when a value is selected

Usage

    <h:selectOneMenu value="#{person.age}"

                     converter="ageConverter">

      <s:selectItems value="#{ages}" var="age" label="#{age}" />

    </h:selectOneMenu>

#### 34.1.5.4. `<s:fileUpload>`

Description

Renders a file upload control. This control must be used within a form with an encoding type of `multipart/form-data`, i.e:

    <h:form enctype="multipart/form-data">

For multipart requests, the Seam Multipart servlet filter must also be configured in `web.xml`:

    <filter>

      <filter-name>Seam Filter</filter-name>

      <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>

    </filter>

    <filter-mapping>

      <filter-name>Seam Filter</filter-name>

      <url-pattern>/*</url-pattern>

    </filter-mapping>

Configuration

The following configuration options for multipart requests may be configured in components.xml:

- `createTempFiles` — if this option is set to true, uploaded files are streamed to a temporary file instead of in memory.

- `maxRequestSize` — the maximum size of a file upload request, in bytes.

Here's an example:

    <component class="org.jboss.seam.web.MultipartFilter">

      <property name="createTempFiles">true</property>

      <property name="maxRequestSize">1000000</property>

    </component>

Attributes

- `data` — this value binding receives the binary file data. The receiving field should be declared as a `byte[]` or `InputStream` (required).

- `contentType` — this value binding receives the file's content type (optional).

- `fileName` — this value binding receives the filename (optional).

- `fileSize` — this value binding receives the file size (optional).

- `accept` — a comma-separated list of content types to accept, may not be supported by the browser. E.g. `"images/png,images/jpg"`, `"images/*"`.

- `style` — The control's style

- `styleClass` — The control's style class

Usage

    <s:fileUpload id="picture" data="#{register.picture}"

                  accept="image/png"

                  contentType="#{register.pictureContentType}" />

### 34.1.6. Other

#### 34.1.6.1. `<s:cache>`

Description

Cache the rendered page fragment using JBoss Cache. Note that `<s:cache>` actually uses the instance of JBoss Cache managed by the built-in `pojoCache` component.

Attributes

- `key` — the key to cache rendered content, often a value expression. For example, if we were caching a page fragment that displays a document, we might use `key="Document-#{document.id}"`.

- `enabled` — a value expression that determines if the cache should be used.

- `region` — a JBoss Cache node to use (different nodes can have different expiry policies).

Usage

    <s:cache key="entry-#{blogEntry.id}" region="pageFragments">

      <div class="blogEntry">

        <h3>#{blogEntry.title}</h3>

        <div>

          <s:formattedText value="#{blogEntry.body}"/>

        </div>

        <p>

          [Posted on&#160;

          <h:outputText value="#{blogEntry.date}">

            <f:convertDateTime timezone="#{blog.timeZone}" locale="#{blog.locale}"

                               type="both"/>

          </h:outputText>]

        </p>

      </div>

    </s:cache>

#### 34.1.6.2. `<s:resource>`

Description

A tag that acts a file download provider. It must be alone in the JSF page. To be able to use this control, web.xml must be set up as follows.

Configuration

    <servlet>

       <servlet-name>Document Store Servlet</servlet-name>

       <servlet-class>org.jboss.seam.document.DocumentStoreServlet</servlet-class>

    </servlet>

    <servlet-mapping>

       <servlet-name>Document Store Servlet</servlet-name>

       <url-pattern>/seam/docstore/*</url-pattern>

    </servlet-mapping>

Attributes

- `data` — Data that should be downloaded. May be a java.util.File, an InputStream or a byte array.

- `fileName` — Filename of the file to be served

- `contentType` — content type of the file to be downloaded

- `disposition` — disposition to use. Default is inline

Usage

Here is an example on how to use the tag:

    <s:resource xmlns="http://www.w3.org/1999/xhtml"

        xmlns:s="http://jboss.org/schema/seam/taglib"

        data="#{resources.data}"

        contentType="#{resources.contentType}"

        fileName="#{resources.fileName}" />

The bean named `resources` is some backing bean that given some request parameters servers a specific file, see `s:download`.

#### 34.1.6.3. `<s:download>`

Description

Builds a RESTful link to a `<s:resource>`. Nested `f:param` build up the url.

- `src` — Resource file serving files.

Attributes

    <s:download src="/resources.xhtml">

        <f:param name="fileId" value="#{someBean.downloadableFileId}"/>

    </s:download>

Will produce something like: `http://localhost/resources.seam?fileId=1`

#### 34.1.6.4. `<s:graphicImage>`

Description

An extended `<h:graphicImage>` that allows the image to be created in a Seam Component; further transforms can be applied to the image.

All attributes for `<h:graphicImage>` are supported, as well as:

Attributes

- `value` — image to display. Can be a path `String` (loaded from the classpath), a `byte[]`, a `java.io.File`, a `java.io.InputStream` or a `java.net.URL`. Currently supported image formats are `image/png`, `image/jpeg`, `image/gif` and `image/bmp`.

- `fileName` — if not specified the served image will have a generated file name. If you want to name your file, you should specify it here. This name should be unique

Transformations

To apply a transform to the image, you would nest a tag specifying the transform to apply. Seam currently supports these transforms:

`<s:transformImageSize>`

  - `width` — new width of the image

  - `height` — new height of the image

  - `maintainRatio` — if `true`, and one of `width`/`height` are specified, the image will be resized with the dimension not specified being calculated to maintain the aspect ratio.

  - `factor` — scale the image by the given factor

`<s:transformImageBlur>`

  - `radius` — perform a convolution blur with the given radius

`<s:transformImageType>`

  - `contentType` — alter the type of the image to either `image/jpeg` or `image/png`

It's easy to create your own transform - create a `UIComponent` which implements `org.jboss.seam.ui.graphicImage.ImageTransform`. Inside the `applyTransform()`method use `image.getBufferedImage()` to get the original image and `image.setBufferedImage()` to set your transformed image. Transforms are applied in the order specified in the view.

Usage

    <s:graphicImage rendered="#{auction.image ne null}"

                    value="#{auction.image.data}">

      <s:transformImageSize width="200" maintainRatio="true"/>

    </s:graphicImage>

#### 34.1.6.5. `<s:remote>`

Description

Generates the Javascript stubs required to use Seam Remoting.

Attributes

- `include` — a comma-separated list of the component names (or fully qualified class names)for which to generate Seam Remoting Javascript stubs. See Chapter 26, Remoting for more details.

Usage

    <s:remote include="customerAction,accountAction,com.acme.MyBean"/>

## 34.2. Annotations

Seam also provides annotations to allow you to use Seam components as JSF converters and validators:

`@Converter`

      @Name("itemConverter")

      @BypassInterceptors

      @Converter

      public class ItemConverter implements Converter {

         @Transactional

         public Object getAsObject(FacesContext context, UIComponent cmp, String value) {

            EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");

            entityManager.joinTransaction();

            // Do the conversion

         }

         public String getAsString(FacesContext context, UIComponent cmp, Object value) {

            // Do the conversion

         }

      }

      <h:inputText value="#{shop.item}" converter="itemConverter" />

  Registers the Seam component as a JSF converter. Shown here is a converter which is able to access the JPA EntityManager inside a JTA transaction, when converting the value back to it's object representation.

`@Validator`

      @Name("itemValidator")

      @BypassInterceptors

      @org.jboss.seam.annotations.faces.Validator

      public class ItemValidator implements javax.faces.validator.Validator {

         public void validate(FacesContext context, UIComponent cmp, Object value)

               throws ValidatorException {

            ItemController ItemController = (ItemController) Component.getInstance("itemController");

            boolean valid = itemController.validate(value);

            if (!valid) {

               throw ValidatorException("Invalid value " + value);

            }

         }

      }

      <h:inputText value="#{shop.item}" validator="itemValidator" />

  Registers the Seam component as a JSF validator. Shown here is a validator which injects another Seam component; the injected component is used to validate the value.

- PrevChapter 33. Built-in Seam components
- Top of page
- Front page
- NextChapter 35. JBoss EL