2014-11-08 69 views
0

我有以下addService.xhtml如何從selectOneMenu組件中獲取所選項目的值?

<html xmlns="http://www.w3.org/1999/xhtml" 
xmlns:h="http://java.sun.com/jsf/html" 
xmlns:f="http://java.sun.com/jsf/core" 
xmlns:p="http://primefaces.org/ui"> 

<h:head><title>Add Service</title></h:head> 
<h:body> 
    <h:form> 
     <p:outputLabel for="name" value="Service Name" /> 
     <p:inputText id="name" value="#{serviceMB.name}"></p:inputText> 

     <p:outputLabel for="categoryCompId" value="Service Category" /> 
     <p:selectOneMenu id="categoryCompId" value="#{serviceMB.selectedCategory}" > 
      <f:selectItem itemLabel="Select Category" itemValue="" noSelectionOption="true" /> 
      <f:selectItems value="#{serviceMB.categories}" var="category" itemLabel="#{category.name}" itemValue="#{category}"/> 
     </p:selectOneMenu> 
     <p:commandButton id="saveService" value="Save" action="#{serviceMB.saveServiceAndExit}"/> 
    </h:form> 
</h:body> 

而下面的託管bean

@Component 
@Controller 
@Scope(value = "request") 
@ManagedBean(name="serviceMB") 
@RequestScoped 
public class ServicesManagedBean implements Serializable { 
    private Category selectedCategory; 
    private String name; 
    public Category getSelectedCategory() { 
     return selectedCategory; 
    } 
    public void setSelectedCategory(Category selectedCategory) { 
     this.selectedCategory = selectedCategory; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public List<Category> getCategories() { 
     return categoryService.getCategories(); 
    } 

}

setSelectedCategory()方法不會被調用,selectedCategory場總是null,儘管我在<p:selectOneMenu中使用它。我的代碼有什麼問題嗎?

我已經添加了一個轉換器,但是當我使用Object selectedObject = ((HtmlSelectOneMenu) arg1).getValue();時,它也會返回null。

+0

您對管理bean類多餘的註釋。他們爲什麼在那裏? – Tiny 2014-11-08 08:14:54

+0

我需要在託管bean中注入一個Spring服務bean。所以,我需要這個託管bean在Spring容器中可見。 – user3377708 2014-11-08 08:58:23

回答

0

您只能在JSF輸入中傳遞字符串和基本類型。對於複雜的對象,你需要一個轉換器

<p:selectOneMenu id="categoryCompId" value="#{serviceMB.selectedCategory}" 
    converter="categoryConverter"> 
    <f:selectItem itemLabel="Select Category" itemValue="#{null}" noSelectionOption="true" /> 
    <f:selectItems value="#{serviceMB.categories}" var="category" itemLabel="#{category.name}" itemValue="#{category}"/> 
</p:selectOneMenu> 
+0

我已經添加了一個轉換器,但是當我使用Object selectedObject =((HtmlSelectOneMenu)arg1).getValue();在「getAsObject」方法中,它也返回null。 – user3377708 2014-11-08 08:10:17

+0

這不是應該如何實現轉換器。看看這裏:[http://stackoverflow.com/questions/8001079/how-create-a-custom-coverter-in-jsf-2](http://stackoverflow.com/questions/8001079/how-create-a -custom-coverter合JSF-2) – 2014-11-09 10:23:46

相關問題