Sunday, November 9, 2008

The SELECT component - struts 2

The select component is perhaps the most common collection-based
UI component comes with struts 2. In a java web application, it's common to build these list of options from a Collection, Map or Arrays of data. The fallowing snippet shows the simplest use case of the select UI component.

<s:select name="userType" list="{'Administrator','Power User','Guest'}" />

Here, we have supplied an OGNL list literal as the list value of the select box. This render the fallowing HTML markup into the page.

<select name="userType" id="registerUserForm_userType">
<option value="Administrator">Administrator</option>
<option value="Power User">Power User</option>
<option value="Guest">Guest</option>

Here, "registerUserForm" is the my action name submitted with the form. But, most of the time, we may need to create select UI component with more advance Collection data. In this case, it may be list of UserType objects. Suppose, we have a class as fallows.

public class UserType{
private int userTypeId,
private String userTypeName,
// .....

Now, we want to create the select UI component from a List of UserType objects. In this case, we need to have userTypeId as the value and userTypeName as option contents (what user can see from select box). Here, the userTypeId should be a key attribute in the matching database table.

<s:select list="userType" key="userType" listKey="userTypeId"

userType is the list of UserType objects which is already exposed into the ValueStack through an action class. listKey and listValue are important tow attributes, when it comes to this kind advance data types.

  • listKey - The property of the List’s elements to be used for the value submitted when those elements are complex types; key by default.
  • listValue - The property of the List’s elements to be used for the content of the option when those elements are complex types in other words, the string seen by the user; value by default.

Here is the rendered HTML from the above UI components.

<select id="registerUserForm_userType" name="userType">
<option value="1">administrator</option>
<option value="2">power</option>
<option value="3">guest</option>