Seam #Scope(ScopeType.CONVERSATION) behaves like request scoped - jsf

I am trying to implement a function where an h:commandButton component is used to produce a row of the h:dataTable with each button click. I'm testing this using a string list. When the page is first loaded, the function works fine, with the button click producing a row with value "New Item". however, when I click it the second time, the ArrayList from the ActionBean backbean seems to be reallocated. What am I doing wrong?
Action Bean:
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.ScopeType;
import jp.co.dir.bf.common.AppLogger;
import jp.co.dir.bf.front.common.BaseBean;
#Scope(ScopeType.CONVERSATION)
#Name("ActionBean")
public class ActionBean extends BaseBean {
private AppLogger appLogger;
private List<String> list = new ArrayList<String>();
public ActionBean() {
appLogger = new AppLogger(Logger.getLogger(ActionBean.class));
}
public void init(){
appLogger.showDebug("The Form is loaded");
appLogger.showDebug("Initial Size: "+ list.size());
}
public AppLogger getAppLogger() {
return appLogger;
}
public void setAppLogger(AppLogger appLogger) {
this.appLogger = appLogger;
}
public List<String> getList(){
return list;
}
public void addToList(){
list.add(new String("New Item"));
/////This is always printing 1 after each add.
appLogger.showDebug("Item added: "+ list.size());
}
public void setList(List<String> list){
this.list = list;
}
}
The xhtml:
<h:commandButton value = "Add New" >
<p:ajax listener="#{ActionBean.addToList}" update="table"/>
</h:commandButton>
<h:dataTable id = "table" value ="#{ActionBean.list}" var = "item">
<h:column>
<h:outputText value ="#{item}"/>
</h:column>
</h:dataTable>

I've fixed the issue. It's the silliness on my part. I forgot to add the
#Begin(join = true) annotation on init() so init is getting called on each load, instead of being called only once for every conversation. Hope somebody finds this helpful. The new Action Bean code is now:
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.ScopeType;
import jp.co.dir.bf.common.AppLogger;
import jp.co.dir.bf.front.common.BaseBean;
#Scope(ScopeType.CONVERSATION)
#Name("ActionBean")
public class ActionBean extends BaseBean {
private AppLogger appLogger;
private List<String> list = new ArrayList<String>();
public ActionBean() {
appLogger = new AppLogger(Logger.getLogger(ActionBean.class));
}
#Begin(join = true) ///this is the part that is updated
public void init(){
appLogger.showDebug("The Form is loaded");
appLogger.showDebug("Initial Size: "+ list.size());
}
public AppLogger getAppLogger() {
return appLogger;
}
public void setAppLogger(AppLogger appLogger) {
this.appLogger = appLogger;
}
public List<String> getList(){
return list;
}
public void addToList(){
list.add(new String("New Item"));
/////This is always printing 1 after each add.
appLogger.showDebug("Item added: "+ list.size());
}
public void setList(List<String> list){
this.list = list;
}
}

Related

What is the best practice to Manage Facade pattern for EJB session bean?

Hello,
I would like to know the best practice for managing Facades.
The main objective of my project:
Once connected via a login system, we arrive on our account page. Depending on the status of the user (project manager or executant) we can access either the project itself as well as each of its phases (status: project manager) or phases only (status: executant).
In this project, i use entities, i created a persistence unit, and used the Facade pattern to manipulate my database.
In my Netbeans, if I do New > Sessions Bean for Entity Classes, and let say that I select Example entity, then Netbeans would generate public abstract class AbstractFacade<T> {...} with many methode and
#Stateless
public class ExampleFacade extends AbstractFacade<User> {...}
for all entities i have select. For all Facade i use one ManagerBean and i use :
#EJB
private ExampleFacade exempleFacade;
in him .
I have a problem recovering data from other bean managers because for get projet or phase i have use #RequestScope because in .xhtml get param in URL. After search on google, i understand why i can't .
For resolv my problem, i have create a general manager for all facade.
My project works perfectly but I want to know if it's the best practice and if it's secure?
I ask myself it's a question to progress in my learning of jee and jsf
This is my generalManager
package logic;
import facade.PhasesFacade;
import facade.PostesFacade;
import facade.ProjetsFacade;
import facade.UtilisateursFacade;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import model.Phases;
import model.Projets;
import model.Utilisateurs;
/**
*
* #author valibert
*/
#Named(value = "generalManager")
#SessionScoped
public class GeneralManager implements Serializable {
private Utilisateurs currentUser;
private Projets currentProjet;
private Phases currentPhase;
ArrayList<Utilisateurs> listUtilisateurs;
ArrayList<Projets> listProjets;
ArrayList<Phases> listPhases;
private String validForm;
private String mailUtil;
private String mdpUtil;
private int idProjet;
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage();
#ManagedProperty(value = "#{param.idProjet}")
private String idProjetResquest;
#EJB
private PhasesFacade phasesFacade;
#EJB
private PostesFacade postesFacade;
#EJB
private ProjetsFacade projetsFacade;
#EJB
private UtilisateursFacade utilisateursFacade;
/**
* Creates a new instance of generalManager
*/
public GeneralManager() {
}
public Utilisateurs getCurrentUser() {
return currentUser;
}
public void setCurrentUser(Utilisateurs currentUser) {
this.currentUser = currentUser;
}
public Projets getCurrentProjet() {
return currentProjet;
}
public void setCurrentProjet(Projets currentProjet) {
this.currentProjet = currentProjet;
}
public Phases getCurrentPhase() {
return currentPhase;
}
public void setCurrentPhase(Phases currentPhase) {
this.currentPhase = currentPhase;
}
public ArrayList<Utilisateurs> getListUtilisateurs() {
return listUtilisateurs;
}
public void setListUtilisateurs(ArrayList<Utilisateurs> listUtilisateurs) {
this.listUtilisateurs = listUtilisateurs;
}
public ArrayList<Projets> getListProjets() {
return listProjets;
}
public void setListProjets(ArrayList<Projets> listProjets) {
this.listProjets = listProjets;
}
public ArrayList<Phases> getListPhases() {
return listPhases;
}
public void setListPhases(ArrayList<Phases> listPhases) {
this.listPhases = listPhases;
}
public PhasesFacade getPhasesFacade() {
return phasesFacade;
}
public void setPhasesFacade(PhasesFacade phasesFacade) {
this.phasesFacade = phasesFacade;
}
public PostesFacade getPostesFacade() {
return postesFacade;
}
public void setPostesFacade(PostesFacade postesFacade) {
this.postesFacade = postesFacade;
}
public ProjetsFacade getProjetsFacade() {
return projetsFacade;
}
public void setProjetsFacade(ProjetsFacade projetsFacade) {
this.projetsFacade = projetsFacade;
}
public UtilisateursFacade getUtilisateursFacade() {
return utilisateursFacade;
}
public void setUtilisateursFacade(UtilisateursFacade utilisateursFacade) {
this.utilisateursFacade = utilisateursFacade;
}
public String getValidForm() {
return validForm;
}
public void setValidForm(String validForm) {
this.validForm = validForm;
}
public String getMailUtil() {
return mailUtil;
}
public void setMailUtil(String mailUtil) {
this.mailUtil = mailUtil;
}
public String getMdpUtil() {
return mdpUtil;
}
public void setMdpUtil(String mdpUtil) {
this.mdpUtil = mdpUtil;
}
public String getIdProjetResquest() {
return idProjetResquest;
}
public void setIdProjetResquest(String idProjetResquest) {
this.idProjetResquest = idProjetResquest;
}
public int getIdProjet() {
return idProjet;
}
public void setIdProjet(int idProjet) {
this.idProjet = idProjet;
}
//Méthode
public String submitFormLogin(){
currentUser = utilisateursFacade.findOne(mailUtil);
if ((utilisateursFacade.findOne(mailUtil).getMdpUtil().equals(mdpUtil)) && (utilisateursFacade.findOne(mailUtil).getMailUtil().equals(mailUtil)) ){
currentUser = utilisateursFacade.findOne(mailUtil);
validForm = "toCompteFromIndex";
return validForm;
}
currentUser = new Utilisateurs();
message.setSeverity(FacesMessage.SEVERITY_INFO);
message.setSummary("L'utilisateur ou le mot de passe n'est pas valide merci de rééssayer");
message.setDetail("Message detail.");
context.addMessage("formConnection", message);
validForm = "";
return validForm;
}
public void onload(){
try {
idProjet = Integer.parseInt(idProjetResquest);
currentProjet = projetsFacade.findByIdAndUserManager(idProjet, currentUser.getIdUtil());
} catch (NumberFormatException e){
idProjetResquest = "404";
}
}
#PostConstruct
public void initUtilisateurs(){
this.listUtilisateurs = new ArrayList();
this.listUtilisateurs.addAll(utilisateursFacade.findAll());
}
}
and this is a view for example
<ui:composition template="/templates.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<f:metadata>
<f:viewParam id="idProjet" name="idProjet" value="#{generalManager.idProjetResquest}" required="true" />
<f:viewAction action="#{generalManager.onload}" />
</f:metadata>
<ui:define name="content-main">
<h2>Chef Projet #{generalManager.currentUser.prenomUtil}</h2>
<h2>Projet #{generalManager.currentProjet.libelleProj}</h2>
<p>Date du début du projet :<h:outputText value="#{generalManager.currentProjet.dateDebutProj}" >
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:outputText></p>
<p>Phases du projet</p>
<ul>
<ui:repeat value="#{generalManager.phasesFacade.findPhaseByProjet(projetsManager.projetChoose.idProjet)}" var="itemPhase">
<li>
<h:outputLink value="../phases/View.xhtml" >
<f:param name="idPhase" value="#{itemPhase.idPhase}" />
<h:outputText value="#{itemPhase.libellePhase}"/>
</h:outputLink>
</li>
</ui:repeat>
</ul>
</ui:define>
thank you in advance

setPropertyActionListener not working after a action

I have a grid with a list of objects and I am trying to create a basic CRUD. Updates and deletes are going quite fine and without any problems, however, when I try to perform a edit on the selected object the setPropertyActionListener that I've set isn't performing as expected. I've searched on several threads but no success.
Here goes my code:
On my crud-aplicacoes.html I gotta a grid and this is the code of my button where I set my setPropertyActionListener and also my action which goes to action ="editar-aplicacao" that is another page. I'm getting my property aplicacaoSelecionada always null.
<p:commandButton icon="ui-icon-pencil"
title="#{msg['label.button.editar']}" action="editar-aplicacao"
actionListener="#{aplicacoesMB.editarAplicacao}">
<f:setPropertyActionListener
target="#{aplicacoesMB.aplicacaoSelecionada}" value="#{app}" />
</p:commandButton>
My managed bean:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import org.primefaces.model.DualListModel;
import br.com.cnen.enums.SituacaoAplicacaoeEnum;
import br.com.cnen.vo.AplicacaoVO;
import br.com.cnen.vo.PerfilVO;
import br.com.cnen.web.facade.AplicacoesFacade;
#RequestScoped
#ManagedBean(name = "aplicacoesMB")
public class AplicacoesMB extends BeanAbstract {
private static final long serialVersionUID = 1L;
private List<AplicacaoVO> listaAplicacoes;
private AplicacaoVO aplicacaoSelecionada;
private PerfilVO perfilSelecionado;
private boolean edicaoExibicao;
#Inject
private AplicacoesFacade facadeAplicacao;
private List<PerfilVO> source;
private List<PerfilVO> target;
private DualListModel<PerfilVO> dualListPerfil;
#PostConstruct
public void carregarAplicacoes() {
listaAplicacoes = facadeAplicacao.listarTodos();
this.edicaoExibicao = false;
dualListPerfil = new DualListModel<PerfilVO>();
}
public List<PerfilVO> perfis() {
return facadeAplicacao.carregarComboPerfis();
}
public List<SituacaoAplicacaoeEnum> comboStatus() {
List<SituacaoAplicacaoeEnum> lista = new ArrayList<SituacaoAplicacaoeEnum>();
for (SituacaoAplicacaoeEnum current : SituacaoAplicacaoeEnum.values()) {
lista.add(current);
}
return lista;
}
public String editarAplicacao() {
this.edicaoExibicao = false;
pickList();
return "editar-aplicacao";
}
public String visualizarAplicacao() {
this.edicaoExibicao = true;
return "editar-aplicacao";
}
public void excluirAplicacao() {
facadeAplicacao.remover(this.aplicacaoSelecionada);
this.carregarAplicacoes();
this.addMensagem("A exclusão foi realizada com sucesso.", FacesMessage.SEVERITY_INFO);
}
public void bloquearAplicacao() {
this.aplicacaoSelecionada.setSituacao(SituacaoAplicacaoeEnum.BLOQUEADO);
facadeAplicacao.bloquear(this.aplicacaoSelecionada);
this.addMensagem("O bloqueio foi realizado com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void desbloquearAplicacao() {
this.aplicacaoSelecionada
.setSituacao(SituacaoAplicacaoeEnum.DESBLOQUEADO);
facadeAplicacao.desbloquear(this.aplicacaoSelecionada);
this.addMensagem("O desbloqueio com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void alterarAplicacao(){
facadeAplicacao.alterar(aplicacaoSelecionada);
this.addMensagem("O atualização foi realizada com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void addPerfil(){
}
public void pickList(){
source = facadeAplicacao.carregarComboPerfis();
target = new ArrayList<PerfilVO>();
if(aplicacaoSelecionada!=null)
target = aplicacaoSelecionada.getListaPerfis();
dualListPerfil = new DualListModel<PerfilVO>(source, target);
}
/**
*
* Getts and setters
*
*/
public List<AplicacaoVO> getListaAplicacoes() {
return listaAplicacoes;
}
public AplicacaoVO getAplicacaoSelecionada() {
return aplicacaoSelecionada;
}
public void setAplicacaoSelecionada(AplicacaoVO aplicacaoSelecionada) {
this.aplicacaoSelecionada = aplicacaoSelecionada;
System.out.println("-> "+ aplicacaoSelecionada.getAplicaoId());
}
public PerfilVO getPerfilSelecionado() {
return perfilSelecionado;
}
public void setPerfilSelecionado(PerfilVO perfilSelecionado) {
this.perfilSelecionado = perfilSelecionado;
}
public boolean isEdicaoExibicao() {
return edicaoExibicao;
}
public List<PerfilVO> getSource() {
return source;
}
public void setSource(List<PerfilVO> source) {
this.source = source;
}
public List<PerfilVO> getTarget() {
return target;
}
public void setTarget(List<PerfilVO> target) {
this.target = target;
}
public DualListModel<PerfilVO> getDualListPerfil() {
return dualListPerfil;
}
public void setDualListPerfil(DualListModel<PerfilVO> dualListPerfil) {
this.dualListPerfil = dualListPerfil;
}
}
On my editarAplicacao() I can't access the property because it is always going null. Any thoughts on this issue?
Your concrete problem is caused by (ab)using actionListener instead of action to perform a business action. All actionListeners are invoked in the very same order as they have been attached on the component and then finally the action is invoked.
In other words, the <f:setPropertyActionListener> is in your particular case invoked after #{aplicacoesMB.editarAplicacao}, which totally explains the symptom you're seeing of the property not being set.
Fix actionListener to be action.
action="#{aplicacoesMB.editarAplicacao}"
Additionally, you can also get rid of <f:propertyActionListener> altogether and pass the property as action method argument.
action="#{aplicacoesMB.editarAplicacao(app)}"
with
public String editarAplicacao(AplicacaoVO aplicacaoSelecionada) {
// ...
}
See also:
Differences between action and actionListener
How can I pass selected row to commandLink inside dataTable?
You can replace
<f:setPropertyActionListener
target="#{aplicacoesMB.aplicacaoSelecionada}" value="#{app}" />
with
<f:attribute name="aplicacao" value="#{app}"></f:attribute>
and in your actionListenerMethod getting the attribute :
this.aplicacaoSelecionada = ((AplicacaoVO) event.getComponent().getAttributes().get("aplicacao"));

Primefaces Picklist is always empty when using Postconstruct

My code below doesn't work, I'm using primefaces picklist and postconstruct annotation to init method with try catch block.
However my picklistbean is empty, I tried all the ways to make it work but none of them worked.
Can anyone provide me working example for picklist, or in my code am I missing something ?
I'm stuck to this problem for so long, I'll be glad if someone helps me.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import org.springframework.beans.factory.annotation.Autowired;
#ManagedBean(name = "pickListBeanTani")
#ViewScoped
public class PickListBeanTani implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<TrvrTani> tanis;
#ManagedProperty(value = "#{TrvrTaniDAO}")
private TrvrTaniDAO tanidao;
public TrvrTaniDAO getTanidao() {
return tanidao;
}
public void setTanidao(TrvrTaniDAO tanidao) {
this.tanidao = tanidao;
}
private List<TrvrTani> sourcetani;
private List<TrvrTani> targettani;
#PostConstruct
public void init(){
try {
sourcetani = new ArrayList<TrvrTani>();
targettani = new ArrayList<TrvrTani>();
tanidao = new TrvrTaniDAO();
List<TrvrTani> taniList = tanidao.findAll();
System.out.println("tanılist" +taniList);
for (TrvrTani tani : taniList) {
sourcetani.add(new TrvrTani(tani.getTaniid(), tani.getTaniadi(), tani
.getTanikodu()));
}
tanis = new DualListModel<TrvrTani>(sourcetani, targettani);
} catch (Exception e) {
throw e;
}
}
public List<TrvrTani> getSourcetani() {
return sourcetani;
}
public void setSourcetani(List<TrvrTani> sourcetani) {
this.sourcetani = sourcetani;
}
public List<TrvrTani> getTargettani() {
return targettani;
}
public void setTargettani(List<TrvrTani> targettani) {
this.targettani = targettani;
}
public DualListModel<TrvrTani> getTanis() {
return tanis;
}
public void setTanis(DualListModel<TrvrTani> tanis) {
this.tanis = tanis;
}
public void onTransferTani(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrTani) item).getTaniadi()).append("<br />");
int tanisize = tanis.getTarget().size();
System.out.println(" ************target************* : "
+ tanis.getTarget().size());
for (int h = 0; h < tanisize; h++) {
/* elemanin adi, id si ve kodu */
String taniadi = tanis.getTarget().get(h).getTaniadi();
System.out.println(" ************taniadi1************* : "
+ taniadi);
Long taniidp = tanis.getTarget().get(h).getTaniid();
System.out.println(" ************taniid2************* : "
+ taniidp);
String tanikodu = tanis.getTarget().get(h).getTanikodu();
System.out.println(" ************tanikodu3************* : "
+ tanikodu);
}
}
FacesMessage msgtani = new FacesMessage();
msgtani.setSeverity(FacesMessage.SEVERITY_INFO);
msgtani.setSummary("Tanı Eklendi");
msgtani.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgtani);
}
}
In PostContruct,your dao class doesn't inject in your bean.Try preRenderView when you want to initialize somethings in your bean.
Also dont use tanidao = new TrvrTaniDAO(); in your bean.TaniDao should be injected by spring with Autowired.
PreRenderView Example
EDIT
Also if you should inject TrvrTaniDAO with jsf managed property.
#ManagedProperty(value = "#{TrvrTaniDAO}")
private TrvrTaniDAO tanidao;

JSF: method not found

I'm getting this error while developping my application
javax.el.MethodNotFoundException: /test.xhtml #18,99
action="#{ComplexeController.saveComplexe}": Method not found:
fr.code.parc.controller.ComplexeController#97aead.saveComplexe()
test.xhtml :
<h:body>
<h1>Génération des Complexes</h1>
<h:form>
Nom Complexe: <h:inputText value="#{ComplexeController.complexe.nomComp}"/><br/>
Nom Zone: <h:selectOneMenu id="nomZone" value="#{ComplexeController.complexe.zoneParc}" converter="#{GenericConverter}">
<f:selectItems value="#{ZoneController.remplireItem()}"/>
</h:selectOneMenu>
<br/>
<h:commandButton action="#{ComplexeController.saveComplexe}" value="Insérer un nouveau complexe"/>
<h:commandButton action="#{ComplexeController.updateComplexe}" value="Modifier un complexe"/>
<br/>
<h:commandLink action="complexe" value="acceuil"/>
</h:form>
</h:body>
the entity Complexe.java
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Complexe generated by hbm2java
*/
#Entity
#Table(name="COMPLEXE"
,schema="PROJET"
)
public class Complexe implements java.io.Serializable {
private String nomComp;
private ZoneParc zoneParc;
private Set<Parc> parcs = new HashSet<Parc>(0);
public Complexe() {
}
public Complexe(String nomComp) {
this.nomComp = nomComp;
}
public Complexe(String nomComp, ZoneParc zoneParc, Set<Parc> parcs) {
this.nomComp = nomComp;
this.zoneParc = zoneParc;
this.parcs = parcs;
}
#Id
#Column(name="NOM_COMP", unique=true, nullable=false, length=30)
public String getNomComp() {
return this.nomComp;
}
public void setNomComp(String nomComp) {
this.nomComp = nomComp;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="NOM_ZONEE")
public ZoneParc getZoneParc() {
return this.zoneParc;
}
public void setZoneParc(ZoneParc zoneParc) {
this.zoneParc = zoneParc;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="complexe")
public Set<Parc> getParcs() {
return this.parcs;
}
#Override
public int hashCode() {
int hash = 0;
hash += (nomComp != null ? nomComp.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 Complexe)) {
return false;
}
Complexe other = (Complexe) object;
if ((this.nomComp == null && other.nomComp != null) || (this.nomComp != null && !this.nomComp.equals(other.nomComp))) {
return false;
}
return true;
}
public void setParcs(Set<Parc> parcs) {
this.parcs = parcs;
}
}
and now ComplexeDaoImpl.java
import config.HibernateUtil;
import fr.code.parc.model.Complexe;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* #author raddaouirami
*/
public class ComplexeDaoImpl implements ComplexeDao{
#Override
public List<Complexe> list() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
List complexes = session.createQuery("from Complexe").list();
t.commit();
return complexes;
}
#Override
public Complexe getComplexe(String nomComp) {
Session session = HibernateUtil.getSessionFactory().openSession();
return (Complexe) session.load(Complexe.class, nomComp);
}
#Override
public void save(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.save(complexe);
t.commit();
}
#Override
public void update(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.update(complexe);
t.commit();
}
#Override
public void remove(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.delete(complexe);
t.commit();
}
}
and Finally ComplexeController.java
import fr.code.parc.dao.ComplexeDao;
import fr.code.parc.dao.ComplexeDaoImpl;
import fr.code.parc.model.Complexe;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
/**
*
* #author raddaouirami
*/
#ManagedBean
#SessionScoped
public class ComplexeController {
private Complexe complexe;
private DataModel listeComplexes;
private int selectedItemIndex;
/**
* Creates a new instance of ComplexeController
*/
public ComplexeController() {
complexe = new Complexe();
}
/* public Complexe getSelected() {
if (complexe == null) {
complexe = new Complexe();
selectedItemIndex = -1;
}
return complexe;
}*/
public DataModel getListeComplexes() {
List<Complexe> liste = new ComplexeDaoImpl().list();
listeComplexes = new ListDataModel(liste);
return listeComplexes;
}
/**
* #return the complexe
*/
public Complexe getComplexe() {
return complexe;
}
/**
* #param complexe the complexe to set
*/
public void setComplexe(Complexe complexe) {
this.complexe = complexe;
}
public String preparationAddComplexe(){
setComplexe(new Complexe());
return "test";
}
public String preparationEditComplexe(){
setComplexe((Complexe)(getListeComplexes().getRowData()));
return "test";
}
public String DeleteComplexe(){
Complexe complexes = (Complexe)(getListeComplexes().getRowData());
ComplexeDao dao = new ComplexeDaoImpl();
dao.remove(complexes);
return "complexe";
}
public String SaveComplexe(){
ComplexeDao dao = new ComplexeDaoImpl();
dao.save(getComplexe());
return "complexe";
}
public String UpdateComplexe(){
ComplexeDao dao = new ComplexeDaoImpl();
dao.update(complexe);
return "complexe";
}
}
How can I solve it?
In view you invoke saveComplexe
action="#{ComplexeController.saveComplexe}"
ComplexeController has only SaveComplexe method.
Either change to
action="#{ComplexeController.SaveComplexe}"
or rename method in ComplexeController to saveComplexe
2 Solutions:
Solution 1.
Change in test.xhtml : complexeController.saveComplexe [Notice first letter in complexeController is in smaller case]
<h:commandButton action="#{complexeController.saveComplexe}" value="Insérer un nouveau complexe"/>
<h:commandButton action="#{complexeController.updateComplexe}" value="Modifier un complexe"/>
Solution 2.
Change in ComplexeController.java:
#ManagedBean(name="ComplexeController ")
#SessionScoped
public class ComplexeController {
....
}
Read the Following Info about Configuring ManagedBeans in JSF:
There are 2 ways to use #ManagedBean to expose a Java Bean class to Managed Bean class.
Way 1.
#ManagedBean
public class ComplexeController{
....
}
In this case the bean exposed with same name but the first letter is smaller case, i.e., you can access the bean in Facelet as
#{complexeController}
Way 2.
#ManagedBean(name="myBean")
public class ComplexeController{
....
}
In this case the bean exposed with same name but the first letter is smaller case, i.e., you can access the bean in Facelet as
#{myBean}
Try to access the ManagedBean with first char to low case
e.g.
action="#{complexeController.saveComplexe}"
instead of
action="#{ComplexeController.saveComplexe}"

Fill selectManyListbox with items from database

I am currently trying to go through the symptoms in a table and show them in a selectManyListbox although the listbox isn't appearing when I compile and run.
index.html says that sym.symptomList and sym.Symptom are unknown properties
index.html
<h:selectManyListbox id ="list1" value="#{sym.symptomList}">
<f:selectItems value="#{sym.Symptom}" var="c"
itemLabel="#{c.symptomName}" itemValue="#{c.symptomId}"/>
</h:selectManyListbox>
Bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.*;
import java.sql.*;
#ManagedBean(name="sym")
#SessionScoped
public class SymptomBean{
Connection con;
Statement ps;
ResultSet rs;
private List symptomList = new ArrayList();
public List getAllSym() {
int i = 0;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(...) //ommitted details
ps = con.createStatement();
rs = ps.executeQuery("select * from symptoms");
while (rs.next()) {
symptomList.add(i, new Symptom(rs.getString(1), rs.getString(2)));
i++;
}
}
catch (Exception e)
{
System.out.println("Error Data : " + e.getMessage());
}
return symptomList;
}
public class Symptom{
public String symptomId;
public String symptomName;
public Symptom(String symptomId, String symptomName){
this.symptomId = symptomId;
this.symptomName = symptomName;
}
public String getSymptomId(){
return symptomId;
}
public String getSymptomName(){
return symptomName;
}
}
}
It's saying sym.symptomList is an unknown property because you do not have a public getter and setter for it, and sym.Symptom doesn't exist at all.
Create a public getter and setter for symptomList, and don't set the value of syptomList in your getAllSym() method. Something like this:
private List symptomList;
public List getSymptomList() {return symptomList;}
public void setSymptomList(List symptomList) {this.symptomList=symptomList;}
public List getAllSym() {
List allSymptoms = new ArrayList();
//DB lookup logic...
while (rs.next()) {
allSymptoms.add(new Symptom(rs.getString(1), rs.getString(2)));
}
//Close connections, error handling, etc...
return allSymptoms;
}
And then your .xhtml would be:
<h:selectManyListbox id ="list1" value="#{sym.symptomList}">
<f:selectItems value="#{sym.allSym}" var="c"
itemLabel="#{c.symptomName}" itemValue="#{c.symptomId}"/>
</h:selectManyListbox>

Resources