1.
HTML代码
最终实现的效果代码,如下所示:
<select>
<option
selected="selected"
value="Monitor">Monitor</option>
<option
value="VCR">VCR</option>
<option value="Standard
Device">Standard Device</option>
<option value="Smart
Device">Smart Device</option>
<option
value="Trunk">Trunk</option>
<option value="Standby
VCR">Standby VCR</option>
</select>
2.
enum代码
publicenum DeviceType {
@XmlEnumValue("Monitor")
MONITOR("Monitor"),
VCR("VCR"),
@XmlEnumValue("Standard Device")
STANDARD_DEVICE("Standard Device"),
@XmlEnumValue("Smart Device")
SMART_DEVICE("Smart Device"),
@XmlEnumValue("Trunk")
TRUNK("Trunk"),
@XmlEnumValue("Standby VCR")
STANDBY_VCR("Standby VCR");
privatefinal String value;
DeviceType(String v) {
value = v;
}
public String value() {
returnvalue;
}
publicstatic DeviceType fromValue(String v)
{
for (DeviceType c: DeviceType.values()) {
if (c.value.equals(v)) {
return c;
}
}
thrownew IllegalArgumentException(v);
}
}
3.
JSF标签:
<h:selectOneMenu
value="#{voutputType.DEVICETYPE}"
converter="voutputDeviceTypeConverter">
<f:selectItems value="#{voutput.deviceTypeList}"/>
</h:selectOneMenu>
主要有三个部分组成
(a)
value="#{voutputType.DEVICETYPE}"
由javabean ,voutputType中的DEVICETYPE属性,确定html代码中<option selected="selected"
value="Monitor">项的值。
voutputType配置信息在"WebRoot"WEB-INF"faces-config.xml:
<managed-bean>
<managed-bean-name>voutputType</managed-bean-name>
<managed-bean-class>
cn.com.gentek.imatrix.xml.jaxb.voutput.ObjVOutputType
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
其中DEVICETYPE属性对应的变量是枚举DeviceType的一个实例。
(b)
converter="voutputDeviceTypeConverter"
类型转换器,在在"WebRoot"WEB-INF"faces-config.xml配置如下:
<converter>
<converter-id>voutputDeviceTypeConverter</converter-id>
<converter-class>
cn.com.gentek.imatrix.ui.VoutDeviceTypeConverter
</converter-class>
</converter>
cn.com.gentek.imatrix.ui.VoutDeviceTypeConverter代码如下:
(实现< select>中<option>的String类型值,与DeviceType类型之间的转换)
publicclass VoutDeviceTypeConverter implements Converter {
public Object
getAsObject(FacesContext context, UIComponent component, String value) {
DeviceType result = null;
if (value == null || value.length() < 1) {
result = null;
} else
result = DeviceType.fromValue(value);
returnresult;
}
public String
getAsString(FacesContext context, UIComponent component, Object value) {
String result = null;
if (value != null) {
if (value instanceof DeviceType)
{
DeviceType temp =
(DeviceType) value;
result = temp.value();
}
}
return result;
}
}
(c)
<f:selectItems value="#{voutput.deviceTypeList}"/>(重点)
由于deviceTypeList对应变量必须是SelectItem(javax.faces.model.SelectItem)列表,所以有必要将DeviceType类型实例的值和对应String类型值,封装在一个SelectItem实例中。实现代码如下:
ArrayList<SelectItem> deviceTypeList = new ArrayList<SelectItem>();
for (int i = 0; i < DeviceType.values().length; i++) {
deviceTypeList.add(new
SelectItem(DeviceType.values()[i],
DeviceType.values()[i].value()));
}
posted on 2008-03-03 16:15
zhan 阅读(2120)
评论(3) 编辑 收藏