JSF: method not found - jsf

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}"

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;

primefaces autocomplete not showing in textBox

I have tried to implement the autocomplete feature in primefaces but suggestions do not show up in my textbox. Can someone show me what I'm missing. theses are codes
udateCategory.xhtml
<p:panel header="Type in Category to Edit" >
<p:outputLabel value="Category Name"/>
<p:autoComplete value="#{categoryBean.selectedCategory}"
completeMethod="#{categoryBean.completeCategory}"
var="cat"
itemLabel="#{cat.categoryName}"
itemValue="#{cat}"
converter="#{catConverter}"
forceSelection="true"/>
<p:commandButton value="Update" action="#{category.saveCategory}"/>
</p:panel>
CategoryBean
public class CategoryBean implements Serializable{
private Category selectedCategory;
/**
* Creates a new instance of CategoryBean
*/
public CategoryBean() {
}
public List<Category> completeCategory (String query){
CategoryManager manager = new CategoryManager();//an instance of the manager
List<Category> suggestions = new ArrayList<>();//an instance of list
List<Category> allCategory = new ArrayList<>(); //populate the allCategory with data fro db
allCategory = manager.getAllCategory();
//checck to see if data exist in allCategory
if(!allCategory.isEmpty()){
System.out.println("kobla : allcategory has data");
}
else
{
System.out.println("kobla: no data in alcategory");
}
for(Category cat : allCategory){
if(cat.getCategoryName().startsWith(query)){
suggestions.add(cat);
}
}
//check to see if data exists in sugestions
if (!suggestions.isEmpty()) {
System.out.println("kobla : suggestions has data");
} else {
System.out.println("kobla: no data in suggestions");
}
return suggestions;
}
/**
* #return the selectedCategory
*/
public Category getSelectedCategory() {
return selectedCategory;
}
/**
* #param selectedCategory the selectedCategory to set
*/
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
}
CategoryConverter
public class CategoryConverter implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value.trim().equals("")){
return null;
}
else{
try{
int id = Integer.parseInt(value);
List<Category> myCategory = new ArrayList<>();//
myCategory = new CategoryManager().getAllCategory();//load data fro db
for(Category cat : myCategory){
if(cat.getCategoryID() == id){
return cat;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null || value ==""){
return null;
}
else
{
return String.valueOf(((Category)value).getCategoryName());
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
this works for me
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class CategoryBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Category selectedCategory;
#PostConstruct
public void init(){
selectedCategory = new Category();
}
public void saveCategory(){
System.out.println("saved "+this.selectedCategory);
}
public List<Category> completeCategory(String query) {
CategoryManager manager = new CategoryManager();// an instance of the
// manager
List<Category> suggestions = new ArrayList<>();// an instance of list
List<Category> allCategory = new ArrayList<>(); // populate the
// allCategory with data
// fro db
allCategory = manager.getAllCategory();
// checck to see if data exist in allCategory
if (!allCategory.isEmpty()) {
System.out.println("kobla : allcategory has data");
} else {
System.out.println("kobla: no data in alcategory");
}
for (Category cat : allCategory) {
if (cat.getCategoryName().startsWith(query)) {
suggestions.add(cat);
}
}
// check to see if data exists in sugestions
if (!suggestions.isEmpty()) {
System.out.println("kobla : suggestions has data");
} else {
System.out.println("kobla: no data in suggestions");
}
return suggestions;
}
/**
* #return the selectedCategory
*/
public Category getSelectedCategory() {
return selectedCategory;
}
/**
* #param selectedCategory
* the selectedCategory to set
*/
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
}
and
import java.io.Serializable;
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int categoryID;
private String categoryName;
public int getCategoryID() {
return categoryID;
}
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Category(int categoryID, String categoryName) {
super();
this.categoryID = categoryID;
this.categoryName = categoryName;
}
public Category() {
super();
}
#Override
public String toString() {
return "Category [categoryID=" + categoryID + ", categoryName="
+ categoryName + "]";
}
}
and
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
#ManagedBean
#RequestScoped
public class CategoryConverter implements Converter, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value.trim().equals("")){
return null;
}
else{
try{
int id = Integer.parseInt(value);
List<Category> myCategory = new ArrayList<>();//
myCategory = new CategoryManager().getAllCategory();//load data fro db
for(Category cat : myCategory){
if(cat.getCategoryID() == id){
return cat;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null || value ==""){
return null;
}
else
{
return String.valueOf(((Category)value).getCategoryName());
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<h:form>
<p:outputLabel value="Category Name" />
<p:autoComplete
value="#{categoryBean.selectedCategory}"
completeMethod="#{categoryBean.completeCategory}"
var="cat"
itemLabel="#{cat.categoryName}"
itemValue="#{cat}"
converter="#{categoryConverter}"
forceSelection="true" />
<p:commandButton value="Update" action="#{categoryBean.saveCategory}" />
</h:form>
</h:body>
</html>

can JSF Still data user login?

Hello all i have one problem between 2 class of JSF Manage bean.
i have 2 class JSF Manage bean one class use for login, one use for user add/edit/delete user table and edit his information when his login.
my login class
import com.DAO.UserBean;
import com.entity.IUser;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* #author MYE
*/
#ManagedBean
#SessionScoped
public class LoginController implements Serializable{
#EJB
private UserBean userBean;
private IUser user;
private boolean admin ;
private boolean mod ;
/** Creates a new instance of LoginController */
public LoginController() {
user = new IUser();
}
//getter / setter
public boolean isMod() {
return mod;
}
public void setMod(boolean mod) {
this.mod = mod;
}
public IUser getUser() {
return user;
}
public void setUser(IUser user) {
this.user = user;
}
public boolean isAdmin() {
return admin ;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public String cplogin() {
if (userBean.userLogin(user.getUsername(), user.getPassword()) != null) {
if(user.getUsername() != null || user.getPassword() != null){
user = userBean.userLogin(user.getUsername(), user.getPassword());
if(user.getGroups().getAdmin() != null){
setAdmin(user.getGroups().getAdmin());
}
if(user.getGroups().getMods() != null){
setMod(user.getGroups().getMods());
}
if(isAdmin() == true || isMod() == true){
return "home";
}else{
return "login";
}
}else {
return "login";
}
} else {
return "login";
}
}
public String logout() {
user = null;
return "login";
}
public boolean isLoggedIn() {
return user != null;
}
}
and my user bean
import com.DAO.UserBean;
import com.entity.Groups;
import com.entity.IUser;
import com.entity.UserGender;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
/**
*
* #author Kency
*/
#ManagedBean
#ViewScoped
public class UserController implements Serializable{
#EJB
private UserBean userBean;
private IUser user;
private LoginController loginsController;
private Groups groups;
private List<SelectItem> enumGender = new ArrayList<SelectItem>();
private UserGender userGender;
public List<SelectItem> getEnumGender() {
return enumGender;
}
public void setEnumGender(List<SelectItem> enumGender) {
this.enumGender = enumGender;
}
public UserGender getUserGender() {
return userGender;
}
public void setUserGender(UserGender userGender) {
this.userGender = userGender;
}
/** Creates a new instance of UserController */
public UserController() {
user = new IUser();
loginsController = new LoginController();
System.out.println(loginsController.getUser());
for(UserGender iGender : UserGender.values()){
enumGender.add(new SelectItem(iGender, iGender.getLabel()));
}
}
#PostConstruct
public Groups construcGroup(){
return groups = new Groups(1, "Memmber");
}
public IUser getUser() {
return user;
}
public void setUser(IUser user) {
this.user = user;
}
public List<IUser> getUserList(){
return userBean.retrieveAllUser();
}
public void updateUser(){
user = userBean.updateUser(user);
}
public void deleteUser (IUser user){
userBean.deleteUser(user);
}
public void showUserdetails(IUser user){
this.user = user;
}
public IUser getUserDetails(){
return user;
}
public String addUser(){
if(loginsController.isAdmin() == false){
user.setGroups(construcGroup());
if(userBean.checkExistName(user.getUsername()) != null && userBean.checkExistEmail(user.getEmail()) != null
|| userBean.checkExistName(user.getUsername()) != null || userBean.checkExistEmail(user.getEmail()) != null){
checkUserEmail("username or email has exist");
}else{
user = userBean.addUser(user);
addMessage("add success");
return "home";
}
}else {
if(userBean.checkExistName(user.getUsername()) != null && userBean.checkExistEmail(user.getEmail()) != null
|| userBean.checkExistName(user.getUsername()) != null || userBean.checkExistEmail(user.getEmail()) != null){
checkUserEmail("username or email has exist");
}else {
user = userBean.addUser(user);
addMessage("add success");
return "ok";
}
}
return "String";
}
public javax.faces.model.SelectItem[] getGroupList()
{
SelectItem[] options = null;
List<Groups> groups = userBean.retrieveAllGroups();
if (groups != null && groups.size() > 0)
{
int i = 0;
options = new SelectItem[groups.size()];
for (Groups iGroups : groups)
{
options[i++] = new SelectItem(iGroups,iGroups.getGroupname());
}
}
return options;
}
public void checkUserEmail(String msg) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,msg,msg));
}
public void addMessage(String msg) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
}
my question is when i use method isAdmin from loginController for userController to check if he is admin he can choose user groups, if he isn't admin he add default groups is member. but isAdmin from loginController return false why? why it not still data when user login?
You need to inject the bean as a managed property.
#ManagedProperty(value="#{loginController}")
private LoginController loginController;
And get rid of the new LoginController() line in the constructor. It would construct a completely separate instance of the bean, not reuse the already-created one in the session scope.

Resources