#ViewScoped calls post construct each time action is performed - jsf

I've asked one thousand of times but no one gives me a valid solution. Please why in my xhtml page the post construct is called all times when i press the button?how can i solve this problem?Please a valid solution. I've read many answers but they don't fit with my problem.I'm in trouble by 1 week.
The scope of my xhtml isn't changed :
update of a render component that updates another component
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:outputLabel for="Name">Name:</p:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<p:outputLabel for="Location">Locations Available:</p:outputLabel>
<p:selectOneMenu id="Location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:selectItems
value="#{addDefaultPackageBean.availableLocations}" />
</p:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.Search()}" value="Ciao" render=":form:Volo" update=":form:Volo :form"></p:commandButton>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo" rendered="#{addDefaultPackageBean.flag}">
<h:panelGrid columns="3" id="voloGrid">
<p:outputLabel for="Volare">Volo:</p:outputLabel>
<p:selectOneMenu for="Volare" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Volare" value="#{addDefaultPackageBean.elelisfly}"
var="Ciao" itemValue="#{Ciao.name}"
itemLabel="#{Ciao.name}" />
</p:selectOneMenu>
<p:commandButton actionListener="#{addDefaultPackageBean.sel()}" value="hotel and escursions" render="#form" update=":form:Hotel :form"/>
</h:panelGrid>
</p:panel>
<p:outputLabel for="Hotel">Hotel:</p:outputLabel>
<p:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</p:selectOneMenu>
<p:message for="Hotel" />
<p:commandButton actionListener="#{addDefaultPackageBean.add}" value="Add" update=":form:Volo :form:Hotel" render="#form" process="#this,:form:Volo,:form:Location"/>
</h:form>
</h:body>
</html>
My bean page:
package beans;
import java.awt.Event;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.view.ViewScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#ViewScoped
public class AddDefaultPackageBean implements Serializable {
/**
*
*/
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private ArrayList<ElementDTO> elelisescursion;
private ArrayList<ElementDTO> elelis;
private ElementDTO[] selectedEscursions;
private String fly;
private String hotel;
private Boolean flag=true;
private Boolean flagdopo=true;
private ArrayList<String> availableLocations;
private ElementDTO flyElem;
#EJB
private ElementMgr elemMgr;
public ElementDTO[] getSelectedEscursions() {
return selectedEscursions;
}
public void setSelectedEscursions(ElementDTO[] selectedEscursions) {
this.selectedEscursions = selectedEscursions;
}
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
this.elelishotel=new ArrayList<ElementDTO>();
this.elelisescursion=new ArrayList<ElementDTO>();
this.elelisfly=new ArrayList<ElementDTO>();
this.availableLocations=new ArrayList<String>();
this.flyElem=new ElementDTO();
}
#PostConstruct
public void init()
{
System.out.print("merda init ");
if(this.getElelisfly().size()==0){System.out.print("Voli vuoto ");}
this.setElelis(elemMgr.getAllElements());
this.selectedEscursions=new ElementDTO[this.getElelis().size()];
this.fly="";
for(ElementDTO e:elelis)
{
if (this.availableLocations.contains(e.getLocation())==false)
{
this.availableLocations.add(e.getLocation());
}
}
}
public String add() {
System.out.print("entrato nell'ultimo step!il mio hotel è "+hotel);
//System.out.print("entrato nell'ultimo step!il mio hotel è "+this.selectedEscursions[0].getName());
/* //assegno location al pacchetto defpackDTO
this.defpackDTO.setLocation(this.getFlyElem().getLocation());
//assegno location a defpackDTO
this.defpackDTO.getElem().add(this.getFlyElem());
//assegno hotel a defpackDTO
this.AssignElemHotelFromSelection();
//assegno escursioni a defpackDTO
for(int i=0;i<this.selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(this.selectedEscursions[i]);
}
defpackMgr.save(defpackDTO);
*/
return "/employee/index?faces-redirect=true";
}
public void sel()
{
System.out.print("ehila"+this.fly );
this.setElelis(this.elemMgr.getAllElementsByLocation(this.defpackDTO.getLocation()));
for(ElementDTO e:elelis)
{
System.out.print("elemento della location Haiti "+e.getName());
}
for(ElementDTO e:elelis)
{
System.out.print("elementisfwefsf dei voli "+e.getName());
}
this.AssignElemFlyFromSelection();
System.out.print(this.fly+"Il volo selezionato per la location è "+this.getFlyElem().getName() );
this.elelisescursion.clear();
this.elelishotel.clear();
for(ElementDTO e:elelis)
{
if(e.getType().equals("Hotel"))
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&((e.getEndingDate().before(this.flyElem.getEndingDate()))))
{
System.out.print("ho un hotel tra gli elementi con le date giuste"+e.getName());
this.getElelishotel().add(e);
}
}
else
{
if(e.getType().equals("Escursion"))
{
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
System.out.print("ho un escursione tra gli elementi con le date giuste"+e.getName());
this.getElelisescursion().add(e);
}
}
}
}
this.setFlag(true);
this.setFlagdopo(true);
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public ArrayList<ElementDTO> getElelisescursion() {
return elelisescursion;
}
public void setElelisescursion(ArrayList<ElementDTO> elelisescursion) {
this.elelisescursion = elelisescursion;
}
public String getFly() {
return fly;
}
public void setFly(String fly) {
this.fly = fly;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getName().equals(this.fly))
{
this.flyElem=elem;
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getName().equals(this.hotel))
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemEscursionFromSelection()
{
for(int i=0;i<selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(selectedEscursions[i]);
}
}
public void Search(){
this.getElelisfly().clear();
String s=defpackDTO.getLocation();
System.out.print("luogo scelto "+s);
this.setElelis(this.elemMgr.getAllElementsByLocation(s));
for(ElementDTO e:elelis)
{
System.out.print("aggiungo volo "+e.getName());
if(e.getType().equals("Flight"))
{
this.getElelisfly().add(e);
System.out.print("aggiungo volo "+e.getName());
}
}
this.setFlag(true);
}
public ArrayList<ElementDTO> getElelis() {
return elelis;
}
public void setElelis(ArrayList<ElementDTO> elelis) {
this.elelis = elelis;
}
public ArrayList<String> getAvailableLocations() {
return availableLocations;
}
public void setAvailableLocations(ArrayList<String> availableLocations) {
this.availableLocations = availableLocations;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public boolean isFlagdopo() {
return flagdopo;
}
public void setFlagdopo(boolean flagdopo) {
this.flagdopo = flagdopo;
}
public ElementDTO getFlyElem() {
return flyElem;
}
public void setFlyElem(ElementDTO flyElem) {
this.flyElem = flyElem;
}
}

Use import javax.faces.bean.ViewScoped; if the managed bean is not a CDI artifact.

Related

why the form is submitted by the SelectOneMenu instead of the submit button

my pb is that when I select an item to display items in the second selectOneMenu () the submit button does not work.
at the second click the button tries to submit the form but (this action emptie the second SOM) as the second SelectOneMenu becomes empty its trigger a validation error.
primefaces 6.1
jsf2.2
tomcat8.5
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<h:panelGroup id="addProjet2" rendered="true">
<table>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2">
</h:outputLabel></td>
<td><p:selectOneMenu id="Client2"
value="#{creerintervention.selected_client}" effect="fade"
style="width:100px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_client}" var="cl"
itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="create_intervention_form:station1_client"
listener="#{creerintervention.getStructureByClient}"
process="Client2" />
</p:selectOneMenu> <p:selectOneMenu id="station1_client"
value="#{creerintervention.selectedStation}" style="width:100px"
filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_Station}"
var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
<p:ajax partialSubmit="false" />
</p:selectOneMenu></td>
</tr>
<tr>
<p:commandButton value="Valider" pdate="create_intervention_form"
id="valide" actionListener="#{creerintervention.addOdm}"
styleClass="ui-priority-primary" />
</tr>
</table>
</h:panelGroup>
</h:form>
ManagedBean
#RequestScoped
#Management(name = "creerintervention")
public class CreerIntervention {
private String matricule;
private agentService agentservice = new agentServiceImpl();
private usersService usersService = new usersServiceImpl();
private clientService clientService = new clientServiceImpl();
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> StationList;
private List<SelectItem> StationList;
private station selectedStation;
private client Selected_client;
{
//*** initialiser la liste des client dans le SelectOnMenu
list_client = clientService.findAll();
}
public void getStructureByClient()
{
// ######## Préparer la liste des nom des clients ######## //
list_Station=stationService.findByRefClient(getSelected_client().getRef());
log.info("La refernce du client est ---"+ Selected_client.getRef());
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.size());
}
public void addOdm(ActionEvent e)
{
log.info("Matricule:" + matricule) ;
log.info("destination:" +destination);
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ selectedStation.getNom_stat());
log.info("objet mission:"+ obj_mission );
log.info("date depart:"+ date_dep );
log.info("date ret:"+ date_retour );
log.info("moyen transp:"+ moyen_transport) ;
log.info("imma:"+ immatriculation) ;
log.info("prise en charge :"+ prise_en_charge) ;
log.info("struct:"+ structure) ;
}
.....
Setters and Getters...
I have get the solution ; the problem was in the Scope the right one is #ViewScoped.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<table>
<tr>
<td><p:outputLabel value="Matricule:" for="Matricule" /></td>
<td><p:inputText id="Matricule"
value="#{teststation.matricule}" size="5" /></td>
</tr>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2"></h:outputLabel> </td>
<td>
<p:panel id="st">
<p:selectOneMenu id="Client2" value="#{teststation.selected_client}">
<f:selectItems value="#{teststation.list_client}" var="cl" itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="station1_client" listener ="#{teststation.getStructureByClient}" />
</p:selectOneMenu>
<p:selectOneMenu id="station1_client" value="#{teststation.selectedStation}" >
<f:attribute name="selected_station" value="#{teststation.selectedStation}" />
<f:selectItems value="#{teststation.list_Station}" var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
</p:selectOneMenu>
</p:panel>
</td>
</tr>
<tr>
<td><h:outputLabel value="Immatriculation:" for="imma"></h:outputLabel> </td>
<td><p:inputText size="20" value="#{teststation.immatriculation}" id="imma"></p:inputText></td>
</tr>
<tr>
<p:growl id="growl" life="2000" />
<td></td>
<td><p:commandButton value="Valider" id="valide" update="errorMessages" actionListener="#{teststation.addOdm}" styleClass="ui-priority-primary" />
</td>
</tr>
</table>
</h:form>
</h:body>
</html>
the ManagedBean
#ViewScoped
#ManagedBean(name = "teststation")
public class TestStation {
private String matricule;
private stationService stationService = new stationServiceImpl();
private clientService clientService = new clientServiceImpl();
public static Logger log = LogManager.getLogger(CreerIntervention.class.getName());
private String nom;
private String client_name;
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> stationList;
private List<SelectItem> stationList;
private String immatriculation;
private String ref_Selected_client;
private String Nom_Selected_client;
private String ref_Selected_station;
private String Nom_Selected_station;
private List<station> station;
private station selectedStation;
private client Selected_client;
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
Map<String, String> selectedStationParam= fc.getExternalContext().getRequestParameterMap();
#PostConstruct
public void initMyBean()
{
log.info("ici PosteConstract"+this.getClass().hashCode());
}
public TestStation()
{
super();
log.info("ici Constract "+this.getClass().hashCode());
}
{
list_client = clientService.findAll();
}
public void updateSelectedStation()
{
log.info("LES updateSelectedStatio ---"+ list_Station.get(0).getNom_stat());
}
public void getStructureByClient()
{
log.info("La refernce du client selectioné est --- "+ Selected_client.getRef());
list_Station=stationService.findByRefClient(getSelected_client().getRef());
stationList= new ArrayList<>();
for (station o : list_Station)
{
stationList.add(new SelectItem(o.getNom_stat(),o.getRef_stat()));
}
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.get(0).getNom_stat());
}
public void addOdm()
{ Nom_Selected_station=selectedStation.getNom_stat();
//log.info("num_odm :" + num_odm) ;
log.info("Matricule:" + matricule) ;
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ Nom_Selected_station);
log.info("imma:"+ immatriculation) ;
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void cancelAction(ActionEvent e)
{
log.info("etat valeur ShowForm555 = ");
}
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getNom_Selected_client() {
return Nom_Selected_client;
}
public void setNom_Selected_client(String nom_Selected_client) {
Nom_Selected_client = nom_Selected_client;
}
public String getRef_Selected_client() {
return ref_Selected_client;
}
public void setRef_Selected_client(String Ref_Selected_client) {
this.ref_Selected_client = Ref_Selected_client;
}
public String getClient_name() {
return client_name;
}
public void setClient_name(String client_name) {
this.client_name = client_name;
}
/*public Map<String, String> getClientList() {
return clientList;
}
public void setClientList(Map<String, String> clientList) {
this.clientList = clientList;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}*/
public String getImmatriculation() {
return immatriculation;
}
public void setImmatriculation(String immatriculation) {
this.immatriculation = immatriculation;
}
public List<station> getStation() {
return station;
}
public void setStation(List<station> station) {
this.station = station;
}
/*public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}*/
/*public Map<String, String> getStationList() {
return stationList;
}
public void setStationList(Map<String, String> stationList) {
stationList = stationList;
}*/
public void setClientList(List<SelectItem> clientList) {
this.clientList = clientList;
}
public List<SelectItem> getStationList() {
return stationList;
}
public void setStationList(List<SelectItem> stationList) {
this.stationList = stationList;
}
public List<SelectItem> getClientList() {
return clientList;
}
public station getSelectedStation() {
return selectedStation;
}
public void setSelectedStation(station selectedStation) {
this.selectedStation = selectedStation;
}
public client getSelected_client() {
return Selected_client;
}
public void setSelected_client(client selected_client) {
Selected_client = selected_client;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}
public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}
public String getRef_Selected_station() {
return ref_Selected_station;
}
public void setRef_Selected_station(String ref_Selected_station) {
this.ref_Selected_station = ref_Selected_station;
}
public String getNom_Selected_station() {
return Nom_Selected_station;
}
public void setNom_Selected_station(String nom_Selected_station) {
Nom_Selected_station = nom_Selected_station;
}
}
the StationConverter
#FacesConverter("StationConverter")
public class StationConverter implements Converter {
public static Logger log = LogManager.getLogger(StationConverter.class.getName());
stationService statServ = new stationServiceImpl();
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
log.info("4- submitted value for Station Converter ********** "+submittedValue);
log.info("5- returned Object for Station Converter ********** "+statServ.findByRef(submittedValue).getNom_stat());
return statServ.findByRef(submittedValue);
} catch (NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Client ID"));
}}
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
log.info(modelValue.getClass());
if (modelValue instanceof station ) {
log.info( "6- la valeur en String Converter Station est ****** "+String.valueOf(((station) modelValue).getNom_stat()));
return String.valueOf(((station) modelValue).getRef_stat());
} else {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Station instance"));
}
}
}

p:columns inside ui:repeat is not working

I'm working on a project that requires a dataTable for each item of a collection, and each of those dataTables has dynamic columns.
Here's an example of what I want to do..
DocsDescriptor.java
package test;
public class DocsDescriptor {
private long id;
private String name;
public DocsDescriptor(long id, String name){
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DocsData.java
package test;
public class DocsData {
private long id;
private String value;
private DocsDescriptor descriptor;
public DocsData(long id, String value, DocsDescriptor descriptor){
this.id = id;
this.value = value;
this.descriptor = descriptor;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public DocsDescriptor getDescriptor() {
return descriptor;
}
public void setDescriptor(DocsDescriptor descriptor) {
this.descriptor = descriptor;
}
}
DocsDocument.java
package test;
import java.util.ArrayList;
import java.util.List;
public class DocsDocument {
private long id;
private List<DocsData> datas;
public DocsDocument(long id){
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<DocsData> getDatas() {
return datas;
}
public void setDatas(List<DocsData> datas) {
this.datas = datas;
}
public void add(DocsData data){
if(this.datas == null) this.datas = new ArrayList<DocsData>();
this.datas.add(data);
}
}
DocsDocumentType.java
package test;
import java.util.ArrayList;
import java.util.List;
public class DocsDocumentType {
private long id;
private String name;
private List<DocsDocument> documents;
public DocsDocumentType(long id, String name){
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DocsDocument> getDocuments() {
return documents;
}
public void setDocuments(List<DocsDocument> documents) {
this.documents = documents;
}
public void add(DocsDocument document){
if(this.documents == null) this.documents = new ArrayList<DocsDocument>();
this.documents.add(document);
}
}
TestController.java
package test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
#ConversationScoped
#Named("test")
public class TestController implements Serializable{
private static final long serialVersionUID = 2433550537340132027L;
#Inject
protected Conversation conversation;
private List<DocsDocumentType> documentTypes;
public void start(){
if(this.conversation.isTransient())
this.conversation.begin();
if(this.conversation != null)
this.conversation.setTimeout(10800000);
}
#PostConstruct
public void init(){
DocsDescriptor dePhone = new DocsDescriptor(1,"Number");
DocsDescriptor deName = new DocsDescriptor(2,"Name");
DocsDescriptor deLastName = new DocsDescriptor(3,"Last Name");
DocsDescriptor dePrice = new DocsDescriptor(4,"Product Price");
DocsDescriptor deCode = new DocsDescriptor(5,"Product Code");
DocsDescriptor deProdName = new DocsDescriptor(6,"Product Name");
DocsDocument jl = new DocsDocument(1);
jl.add(new DocsData(1,"514237797", dePhone));
jl.add(new DocsData(2,"John", deName));
jl.add(new DocsData(3,"Lennon", deLastName));
DocsDocument pm = new DocsDocument(2);
pm.add(new DocsData(4,"45312342", dePhone));
pm.add(new DocsData(5,"Paul", deName));
pm.add(new DocsData(6,"McCartney", deLastName));
DocsDocument rs = new DocsDocument(3);
rs.add(new DocsData(7,"567523534", dePhone));
rs.add(new DocsData(8,"Richard", deName));
rs.add(new DocsData(9,"Starkey", deLastName));
DocsDocument gh = new DocsDocument(3);
gh.add(new DocsData(10,"454623243", dePhone));
gh.add(new DocsData(11,"George", deName));
gh.add(new DocsData(12,"Harrison", deLastName));
DocsDocumentType identity = new DocsDocumentType(1,"Beatles");
identity.add(jl);
identity.add(pm);
identity.add(gh);
identity.add(rs);
DocsDocument iPhone = new DocsDocument(4);
iPhone.add( new DocsData(13,"iPhone 6S",deProdName));
iPhone.add( new DocsData(15,"23452340",deCode));
iPhone.add( new DocsData(16,"$650",dePrice));
DocsDocument nexus = new DocsDocument(5);
nexus.add( new DocsData(13,"Nexus 6P",deProdName));
nexus.add( new DocsData(15,"786338675",deCode));
nexus.add( new DocsData(16,"$600",dePrice));
DocsDocumentType product = new DocsDocumentType(1,"Product");
product.add(iPhone);
product.add(nexus);
this.documentTypes = new ArrayList<DocsDocumentType>();
this.documentTypes.add(identity);
this.documentTypes.add(product);
}
public List<DocsDocumentType> getDocumentTypes() {
return documentTypes;
}
public void setDocumentTypes(List<DocsDocumentType> documentTypes) {
this.documentTypes = documentTypes;
}
}
test.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>TEST</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</h:head>
<h:body>
<f:event type="preRenderView" listener="#{test.start}"/>
<h:panelGroup id="bigArea" style="width : 100%">
<ui:repeat value="#{test.documentTypes}" var="dt">
<p:panelGrid style="width : 750px">
<f:facet name="header">
<p:row>
<p:column style="width : 750px; text-align: left"><h:outputText value="#{dt.name}" /></p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<p:dataTable value="#{dt.documents}" var="doc" emptyMessage="...">
<p:columns value="#{doc.datas}" var="data">
<f:facet name="header"><h:outputText value="#{data.descriptor.name}"/></f:facet>
<h:outputText value="#{data.value}" />
</p:columns>
</p:dataTable>
</p:column>
</p:row>
</p:panelGrid>
</ui:repeat>
</h:panelGroup>
</h:body>
</html>
And here's the output:
http://picpaste.com/Captura_de_pantalla_2015-12-12_a_las_19.11.27_1-0Fd7lEtY.png
I'm using wildfly 9.0.1, primefaces-5.2
Can anybody help me out with a solution or an alternative?
Thank you all!
Value of p:columns cannot refer to var of parent dataTable. Documentation http://www.primefaces.org/showcase/ui/data/datatable/columns.xhtml shows this moment. Actually in your model each row can contain different number of columns. You need to change model:
TableModel:
package test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kit on 14.12.2015.
*
* #author kit
*/
public class TableModel {
private String name;
private List<RowModel> rows = new ArrayList<>();
private List<ColumnModel> columns = new ArrayList<>();
/**
* Getters, Setters
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<RowModel> getRows() {
return rows;
}
public List<ColumnModel> getColumns() {
return columns;
}
}
RowModel:
package test;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kit on 14.12.2015.
*
* #author kit
*/
public class RowModel<T> {
private String name;
private Map<ColumnModel, T> data = new HashMap<>();
/**
* Getters, Setters
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<ColumnModel, T> getData() {
return data;
}
}
ColumnModel:
package test;
/**
* Created by kit on 14.12.2015.
*
* #author kit
*/
public class ColumnModel<T> {
private T data;
/**
* Getters, Setters
*/
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
Modify TestController:
package test;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#ConversationScoped
#Named("test")
public class TestController implements Serializable {
private static final long serialVersionUID = 2433550537340132027L;
#Inject
protected Conversation conversation;
private List<TableModel> tables = new ArrayList<>();
private List<DocsDocumentType> documentTypes;
public void start() {
if (this.conversation.isTransient())
this.conversation.begin();
if (this.conversation != null)
this.conversation.setTimeout(10800000);
}
#PostConstruct
public void init() {
DocsDescriptor dePhone = new DocsDescriptor(1, "Number");
DocsDescriptor deName = new DocsDescriptor(2, "Name");
DocsDescriptor deLastName = new DocsDescriptor(3, "Last Name");
DocsDescriptor dePrice = new DocsDescriptor(4, "Product Price");
DocsDescriptor deCode = new DocsDescriptor(5, "Product Code");
DocsDescriptor deProdName = new DocsDescriptor(6, "Product Name");
DocsDocument jl = new DocsDocument(1);
jl.add(new DocsData(1, "514237797", dePhone));
jl.add(new DocsData(2, "John", deName));
jl.add(new DocsData(3, "Lennon", deLastName));
DocsDocument pm = new DocsDocument(2);
pm.add(new DocsData(4, "45312342", dePhone));
pm.add(new DocsData(5, "Paul", deName));
pm.add(new DocsData(6, "McCartney", deLastName));
DocsDocument rs = new DocsDocument(3);
rs.add(new DocsData(7, "567523534", dePhone));
rs.add(new DocsData(8, "Richard", deName));
rs.add(new DocsData(9, "Starkey", deLastName));
DocsDocument gh = new DocsDocument(3);
gh.add(new DocsData(10, "454623243", dePhone));
gh.add(new DocsData(11, "George", deName));
gh.add(new DocsData(12, "Harrison", deLastName));
DocsDocumentType identity = new DocsDocumentType(1, "Beatles");
identity.add(jl);
identity.add(pm);
identity.add(gh);
identity.add(rs);
DocsDocument iPhone = new DocsDocument(4);
iPhone.add(new DocsData(13, "iPhone 6S", deProdName));
iPhone.add(new DocsData(15, "23452340", deCode));
iPhone.add(new DocsData(16, "$650", dePrice));
DocsDocument nexus = new DocsDocument(5);
nexus.add(new DocsData(13, "Nexus 6P", deProdName));
nexus.add(new DocsData(15, "786338675", deCode));
nexus.add(new DocsData(16, "$600", dePrice));
DocsDocumentType product = new DocsDocumentType(1, "Product");
product.add(iPhone);
product.add(nexus);
this.documentTypes = new ArrayList<DocsDocumentType>();
this.documentTypes.add(identity);
this.documentTypes.add(product);
// Populating tableModel
for (DocsDocumentType docsDocumentType : documentTypes) {
TableModel tableModel = new TableModel();
tableModel.setName(docsDocumentType.getName());
for (DocsDocument docsDocument : docsDocumentType.getDocuments()) {
RowModel<String> rowModel = new RowModel<>();
rowModel.setName(String.valueOf(docsDocument.getId()));
tableModel.getRows().add(rowModel);
for (DocsData docsData : docsDocument.getDatas()) {
ColumnModel<DocsDescriptor> columnModel = findColumn(tableModel, docsData.getDescriptor());
if (columnModel == null) {
columnModel = new ColumnModel<>();
columnModel.setData(docsData.getDescriptor());
tableModel.getColumns().add(columnModel);
}
rowModel.getData().put(columnModel, docsData.getValue());
}
}
tables.add(tableModel);
}
}
private ColumnModel findColumn(TableModel tableModel, DocsDescriptor descriptor) {
for (ColumnModel columnModel : tableModel.getColumns()) {
if (descriptor.equals(columnModel.getData())) {
return columnModel;
}
}
return null;
}
public List<TableModel> getTables() {
return tables;
}
}
And view:
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>TEST</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</h:head>
<h:body>
<f:event type="preRenderView" listener="#{test.start}"/>
<h:panelGroup id="bigArea" style="width : 100%">
<ui:repeat value="#{test.tables}" var="dt">
<p:panelGrid style="width : 750px">
<f:facet name="header">
<p:row>
<p:column style="width : 750px; text-align: left"><h:outputText value="#{dt.name}" /></p:column>
</p:row>
</f:facet>
<p:row>
<p:column>
<p:dataTable value="#{dt.rows}" var="row" emptyMessage="...">
<p:columns value="#{dt.columns}" var="col">
<f:facet name="header"><h:outputText value="#{col.data.name}"/></f:facet>
<h:outputText value="#{row.data[col]}" />
</p:columns>
</p:dataTable>
</p:column>
</p:row>
</p:panelGrid>
</ui:repeat>
</h:panelGroup>
</h:body>
</html>

Error : javax.el.PropertyNotFoundException: Target Unreachable, 'null' returned null [duplicate]

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
I got this error below when I was running my JSF page.
javax.el.PropertyNotFoundException: Target Unreachable, 'null' returned null..
Warning: /createStaff.xhtml #33,125
value="#{staffBean.staff.firstName}": Target Unreachable, 'null'
returned null javax.el.PropertyNotFoundException: /createStaff.xhtml
#33,125 value="#{staffBean.staff.firstName}": Target Unreachable,
'null' returned null
I don't get why I will run into the error when I use value="#{staffBean.staff.firstName}". There is no problem when I use the value="#{staffBean.userName}" and value="#{staffBean.passWord}" above.
This is my createStaff.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Create Staff</title>
</h:head>
<h:body>
<f:view>
<h:form>
<p:panel id ="panel" header="Staff Creation">
<p:messages id="msgs" />
<h:panelGrid columns="3" columnClasses="label, value">
<h:outputText value="Username: *" />
<p:inputText id="username" value="#{staffBean.userName}" required="true" label="Username">
</p:inputText>
<p:message for="username" />
<h:outputLabel for="pwd1" value="Password 1: *" />
<p:password id="pwd1" value="#{staffBean.passWord}" match="pwd2" label="Password 1" required="true" feedback="true" />
<p:message for="pwd1" />
<h:outputLabel for="pwd2" value="Password 2: *" />
<p:password id="pwd2" value="#{staffBean.passWord}" label="Password 2" required="true" feedback="true" />
<p:message for="pwd2" />
<h:outputText value="First name: *" />
<p:inputText id="firstname" value="#{staffBean.staff.firstName}" required="true" label="Username">
</p:inputText>
<p:message for="firstname" />
<h:outputText value="Last name: *" />
<p:inputText id="lastname" value="#{staffBean.staff.lastName}" required="true" label="Username">
</p:inputText>
<p:message for="lastname" />
<h:outputText value="Last name: *" />
<p:selectOneRadio id="genderconsole" value="#{staffBean.staff.gender}" required="true">
<f:selectItem itemLabel="Male" itemValue="Male" />
<f:selectItem itemLabel="Female" itemValue="Female" />
</p:selectOneRadio>
<p:message for="genderconsole" />
<p:commandButton value="Create Staff"
id="ajax"
update="panel">
</p:commandButton>
</h:panelGrid>
</p:panel>
</h:form>
</f:view>
</h:body>
</html>
This is my StaffBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package managedbean;
import entities.Staff;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import sessionBean.staffSessionBeanLocal;
#Named(value = "staffBean")
#SessionScoped
//#ViewScoped
public class StaffBean implements Serializable {
#EJB
private staffSessionBeanLocal staffSession;
private String userName;
private String passWord;
private String loginStatus;
private Staff staff;
...........
////Code removed
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getLoginStatus() {
return loginStatus;
}
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
}
This is my staff entity.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Staff extends User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String imageURL;
#ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private List<Roles> roles = new ArrayList<Roles>();
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Staff)) {
return false;
}
Staff other = (Staff) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Staff[ id=" + id + " ]";
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
}
This is my User class which Staff class extends from.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String password;
private Timestamp joinDate;
private String userType;
private String gender;
private String email;
private String contactNo;
private String firstName;
private String lastName;
private Timestamp dOB;
private String address;
private String accountStatus;
private int numOfFailLogin;
private String maritalStatus;
private String activationCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.User[ id=" + id + " ]";
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Timestamp getJoinDate() {
return joinDate;
}
public void setJoinDate(Timestamp joinDate) {
this.joinDate = joinDate;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Timestamp getdOB() {
return dOB;
}
public void setdOB(Timestamp dOB) {
this.dOB = dOB;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccountStatus() {
return accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public int getNumOfFailLogin() {
return numOfFailLogin;
}
public void setNumOfFailLogin(int numOfFailLogin) {
this.numOfFailLogin = numOfFailLogin;
}
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
}
You have no property firstName in your entity staff
UPDATE:
Looks like your staffobject is null add:
#PostConstruct
public void init() {
staff = new Stuff();
}
The error suggests that when the "firstName" is being accessed, it cannot be reached. So the "Staff" has not been constructed yet.
Add a method to your managed bean, this will resolve the issue.
#PostConstruct
public void init() {
staff= new Staff ();
}
For better understanding of why you should do it that way and not
Staff staff = new Staff();
JSF - what is the difference between #PostConstruct and direct method call from constructor?

RichFaces dynamic TabPanel

How to implement a simple add/remove dynamic <rich:tabPanel>?
(I've seen people asking this around so I thought postin a Q&A of a simple implementation)
The implementation has 3 custom classes:
Content: contains the values to be displayed in a tab;
ItemTab: contais an UITab object and a Content object;
MyTabs: EJB managed bean that provides access to the tabs and adding/removal methods.
The code is:
Content:
public class Content {
String name;
String job;
String dept;
public Content() {
name = "John Doe";
job = "None";
dept = "None";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
TabItem:
public class TabItem {
UITab component;
Content content;
public TabItem() {
component = new UITab();
content = new Content();
}
public UITab getComponent() {
return component;
}
public void setComponent(UITab tab) {
this.component = tab;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
}
MyTabs:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class MyTabs implements Serializable {
private List<TabItem> tabs;
public MyTabs() {
tabs = new ArrayList<TabItem>();
}
#PostConstruct
private void init() {
createTab();
createTab();
createTab();
}
public void createTab() {
TabItem tab = new TabItem();
tab.getComponent().setId("Tab" + (tabs.size()+1));
tab.getComponent().setHeader("Tab " + (tabs.size()+1));
tab.getContent().setName("John Doe " + (tabs.size()+1));
tab.getContent().setJob("Salesman " + (tabs.size()+1));
tab.getContent().setDept("Sales " + (tabs.size()+1));
tabs.add(tab);
}
public void removeTab(TabItem tab) {
tabs.remove(tab);
}
public List<TabItem> getTabs() {
return tabs;
}
public void setTabs(List<TabItem> tabs) {
this.tabs = tabs;
}
}
tabview.xhtml:
<h:commandLink value="Add Tab"
actionListener="#{myTabs.createTab()}"/>
<rich:tabPanel switchType="client">
<c:forEach items="#{myTabs.tabs}" var="tab">
<rich:tab value="#{tab.component}">
<f:facet name="header">
<h:outputLabel value="#{tab.component.header}"/>
<h:commandLink value=" X" actionListener="#{myTabs.removeTab(tab)}"/>
</f:facet>
<h:panelGrid columns="2">
<h:outputLabel value="Name: "/>
<h:outputLabel value="#{tab.content.name}"/>
<h:outputLabel value="Dept: "/>
<h:outputLabel value="#{tab.content.dept}"/>
<h:outputLabel value="Job: "/>
<h:outputLabel value="#{tab.content.job}"/>
</h:panelGrid>
</rich:tab>
</c:forEach>
</rich:tabPanel>

p:selectonemenu not working (JSF)

I have this problem.
I wanted to create selectOneMenu for custom select some data. But it's not working and i really don't know why. I spent cca 5 hours with this problem. I'm so desperate.
So some my code:
But when i will pick some item from selectonemenu, selected_id is still 0. Still, still. I tried to do almost everything but without result.
I tried this:
<p:selectOneMenu value="#{medicinesBean.selectedBranch}" required="true" effect="fade" id="listComboBox">
<f:selectItems value="#{medicinesBean.branchesForComboBox}" var="itm" itemLabel="#{itm.name}" itemValue="#{itm.id}" />
</p:selectOneMenu>
Backing Bean class:
/* private members */
private ArrayList<BranchDTO> branchesForComboBox = new ArrayList<BranchDTO>();
private BranchDTO selectedBranch;
/* getter and setters ... */
also i tried this with SelectItem[] model but result was same. NOT WORK.
Then i tried it like:
<p:selectOneMenu value="#{medicinesBean.selected_id}" required="true" effect="fade" id="listComboBox">
<f:selectItem itemLabel="First" itemValue="1"/>
<f:selectItem itemLabel="Second" itemValue="2"/>
<f:selectItem itemLabel="Third" itemValue="3"/>
<f:selectItem itemLabel="Fouth" itemValue="4"/>
</p:selectOneMenu>
/* private members */
private int selected_id;
But still 0. When i used object like value for selectonemenu, always null exception was always returned. So i will be glad for any advice for this.
Thanks
brw. backing bean is ViewScoped and data from DAO are correctly returned so some bug will be in component selectonemenu.
Thanks BalusC, so here is my implementation
Backing Bean
/**
* #author Sajmon
*/
package OraclBeans;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import EJBs.ZoznamLiekovEJB;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="zoznamLiekovBean")
#ViewScoped
public class ZoznamLiekovBean implements Serializable {
#EJB
private ZoznamLiekovEJB listOfMedicineEJB;
/* private members */
private ArrayList<ZoznamLiekovDTO> listOfMedicines;
private ArrayList<PobockaDTO> branchesForCombobox = new ArrayList<PobockaDTO>();
private ZoznamLiekovDTO selectedItem;
private PobockaDTO selectedBranch;
//private SelectItem[] branchesOptions;
//private SelectItem selectedOption;
private int selected_id;
public ZoznamLiekovBean() {
}
#PostConstruct
private void init() {
branchesForCombobox = listOfMedicineEJB.getBranches();
listOfMedicines = listOfMedicineEJB.getLists();
}
public void test() {
System.out.println("ID: " + selected_id);
}
/*
private SelectItem[] addItemsToOptions() {
SelectItem[] data = new SelectItem[branchesForCombobox.size()];
for (int i = 0; i < branchesForCombobox.size(); i++) {
data[i] = new SelectItem(branchesForCombobox.get(i).getId(), branchesForCombobox.get(i).getNazov());
}
return data;
}
*/
/* getters and setters */
/*
public SelectItem[] getBranchesOptions() {
return branchesOptions;
}
public void setBranchesOptions(SelectItem[] branchesOptions) {
this.branchesOptions = branchesOptions;
}
public void setSelectedOption(SelectItem selectedOption) {
this.selectedOption = selectedOption;
}
public SelectItem getSelectedOption() {
return selectedOption;
}
*/
public ArrayList<PobockaDTO> getBranchesForCombobox() {
return branchesForCombobox;
}
public void setBranchesForCombobox(ArrayList<PobockaDTO> branchesForCombobox) {
this.branchesForCombobox = branchesForCombobox;
}
public ArrayList<ZoznamLiekovDTO> getListOfMedicines() {
return listOfMedicines;
}
public void setListOfMedicines(ArrayList<ZoznamLiekovDTO> listOfMedicines) {
this.listOfMedicines = listOfMedicines;
}
public PobockaDTO getSelectedBranch() {
return selectedBranch;
}
public void setSelectedBranch(PobockaDTO selectedBranch) {
this.selectedBranch = selectedBranch;
}
public ZoznamLiekovDTO getSelectedItem() {
return selectedItem;
}
public void setSelectedItem(ZoznamLiekovDTO selectedItem) {
this.selectedItem = selectedItem;
}
public int getSelected_id() {
return selected_id;
}
public void setSelected_id(int selected_id) {
this.selected_id = selected_id;
}
}
EJB:
/**
* #author Sajmon
*/
package EJBs;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import OraclDAO.OracleZoznamLiekovDAO;
import java.io.Serializable;
import java.util.ArrayList;
import javax.ejb.Stateless;
#Stateless
public class ZoznamLiekovEJB implements Serializable {
private OracleZoznamLiekovDAO dao = new OracleZoznamLiekovDAO();
public ArrayList<ZoznamLiekovDTO> getLists() {
return dao.getListOfMedicines();
}
public ArrayList<PobockaDTO> getBranches() {
return dao.getBranchesForCombobox();
}
}
DAO:
/**
* #author Sajmon
*/
package OraclDAO;
import DTOs.PobockaDTO;
import DTOs.ZoznamLiekovDTO;
import OraclDAOFactory.OracleDAOFactory;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OracleZoznamLiekovDAO implements Serializable {
private String SELECT_ALL = "SELECT Z.id_zoznamu, P.nazov_pobocky, L.nazov_lieku FROM Zoznam_liekov Z "
+ "JOIN Pobocka P ON (Z.id_pobocky = P.id_pobocky)"
+ "JOIN Liek L ON (Z.id_lieku = L.id_lieku)";
private String SELECT_BRANCHES = "SELECT DISTINCT P.id_pobocky, P.nazov_pobocky FROM Zoznam_liekov Z JOIN Pobocka P ON (Z.id_pobocky = P.id_pobocky)";
public OracleZoznamLiekovDAO() {
}
public ArrayList<PobockaDTO> getBranchesForCombobox() {
ArrayList<PobockaDTO> data = new ArrayList<PobockaDTO>();
PobockaDTO item;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OracleDAOFactory.getOracleDatabaseConnection();
ps = con.prepareStatement(SELECT_BRANCHES);
rs = ps.executeQuery();
while (rs.next()) {
item = new PobockaDTO();
item.setId(rs.getInt(1));
item.setNazov(rs.getString(2));
data.add(item);
}
System.out.println("Data imported to list successfully.");
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return data;
}
public ArrayList<ZoznamLiekovDTO> getListOfMedicines() {
ArrayList<ZoznamLiekovDTO> data = new ArrayList<ZoznamLiekovDTO>();
ZoznamLiekovDTO item;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OracleDAOFactory.getOracleDatabaseConnection();
ps = con.prepareStatement(SELECT_ALL);
rs = ps.executeQuery();
while (rs.next()) {
item = new ZoznamLiekovDTO();
item.setId(rs.getInt(1));
item.getPobocka().setNazov(rs.getString(2));
item.getLiek().setNazov(rs.getString(3));
data.add(item);
}
System.out.println("List of Medicines imported successfully.");
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (con != null) {
try {
con.close();
}
catch (SQLException ex) {
Logger.getLogger(OracleZoznamLiekovDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return data;
}
}
And XHTML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Zoznam liekov - prehľad</title>
<link rel="stylesheet" type="text/css" href="../style.css" />
</h:head>
<h:body>
<div id="out">
<h:form id="mainForm">
<p:selectOneMenu value="#{zoznamLiekovBean.selected_id}" required="true" effect="fade" id="zoznamComboBox">
<f:selectItems value="#{zoznamLiekovBean.branchesForCombobox}" var="itm" itemLabel="#{itm.nazov}" itemValue="#{itm.id}"/>
</p:selectOneMenu>
<p:commandButton immediate="true" styleClass="submitClass" value="Generuj zoznam" update="dialogText" actionListener="#{zoznamLiekovBean.test()}"/>
<p:dataTable style="width: 1100px" widgetVar="zoznamLiekovTable" selection="#{zoznamLiekovBean.selectedItem}" selectionMode="single" rowKey="#{item.id}" var="item" value="#{zoznamLiekovBean.listOfMedicines}" rows="5" rowsPerPageTemplate="5,10,15,20"
paginator="true" paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink}">
<p:column>
<f:facet name="header">ID:</f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column>
<f:facet name="header">Pobočka:</f:facet>
<h:outputText value="#{item.pobocka.nazov}"/>
</p:column>
<p:column>
<f:facet name="header">Liek:</f:facet>
<h:outputText value="#{item.liek.nazov}"/>
</p:column>
</p:dataTable>
<p:dialog widgetVar="test" showEffect="explode" hideEffect="explode">
<h:outputText id="dialogText" value="#{zoznamLiekovBean.selected_id}"/>
</p:dialog>
</h:form>
</div>
</h:body>
</html>
Remove immediate="true" from the commandButton. You are skipping the whole Apply Request Value phase - Update Model value phase with that. That's why your value is always null or 0.
Check this out

Resources