我需要使用h:selectOneMenu,它可以根据bean参数显示项。因此,如果user具有"Admin"角色,则第一项应该是"Admin",第二项应该是"user",反之亦然。这是我的代码示例
<h:selectOneMenu id="role" value="#{adminBean.role}">
<h:panelGroup rendered="#{adminBean.role == 'User'}" >
<f:selectItem itemLabel="User" itemValue="User"/>
<f:selectItem itemLabel="Admin" itemValue="Admin"/>
</h:panelGroup>
<h:panelGroup rendered="#{adminBean.role == 'Admin'}" >
<f:selectItem itemLabel="Admin" itemValue="Admin"/>
<f:selectItem itemLabel="User" itemValue="User"/>
</h:panelGroup>
</h:selectOneMenu>
然而,这段代码根本不起作用,所选列表完全为空
这是实现它的一种方法,使用两个f:selectItem
并根据条件
<h:selectOneMenu id="role" value="#{adminBean.role}">
<f:selectItem itemLabel="#{(adminBean.role == 'User')?'User':'Admin'}"
itemValue="#{(adminBean.role == 'User')?'User':'Admin'}"/>
<f:selectItem itemLabel="#{(adminBean.role == 'User')?'Admin':'User'}"
itemValue="#{(adminBean.role == 'User')?'Admin':'User'}"/>
</h:selectOneMenu>
试试这个方法,希望能成功
<c:set var="role" value="${adminBean.role}"/>
<c:choose><c:when test="${role eq "User" }" >
<h:selectOneMenu id="role" value="#{adminBean.role}" >
<f:selectItem itemLabel="Admin" itemValue="Admin"/>
<f:selectItem itemLabel="User" itemValue="User"/>
</h:selectOneMenu>
</c:when></c:choose>
U可以为Admin
添加类似的条件
PostConstruct solution
<f:selectItems value="#{adminBean.options}">
.
@PostConstruct
public void postConstruct(){
this.role = loggedInUser.getRole();
this.options = service.getOptionsByRole(role);
}
public List<SelectItem> getOptions() {
return options;
}
单行if-else语句解决方案
<f:selectItems value="#{adminBean.role == 'User' ? adminBean.userOptions : adminBean.adminOptions}">
参数传递解决方案
<f:selectItems value="#{adminBean.getOptionsByRole(adminBean.role)">
.
public List<SelectItem> getOptions(String role) {
if (role.equals("User")) {
return userOptions;
}
return adminOptions;
}
条件getter方法(不推荐)
<f:selectItems value="#{adminBean.options">
.
public List<SelectItem> getOptions() {
if (role.equals("User")) {
return userOptions;
}
return adminOptions;
}