"#{loginBean.nom}": Target Unreachable, identifier 'loginBean' resolved to null - jsf

I try every solution but still have this problem:
/Acceuil.xhtml #19,30 value="#{loginBean.nom}": Target Unreachable, identifier 'loginBean' resolved to null
I use tomcat 7 as server.
Can you help me to find the problem?

i use two bean
this is LoginBean:
package tn.gestiondintervention.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import tn.gestiondintervention.model.Login;
import tn.gestiondintervention.service.LoginService;
import tn.gestiondintervention.service.impl.LoginServiceImpl;
#ManagedBean(name = "loginBean")
#SessionScoped
public class LoginBean {
private List<Login> loginList;
private String nom;
private String matricule;
public List<Login> getLoginList() {
loginList=new ArrayList<Login>();
LoginService loginService= new LoginServiceImpl();
loginList=loginService.listLogin();
return loginList;
}
public void setLoginList(List<Login> loginList) {
this.loginList = loginList;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String authentification()
{
LoginService loginService= new LoginServiceImpl();
Login login=loginService.getLogin(getMatricule());
if (login == null) {
return "erroracceuil";
} else {
if (login.getNom() == "admin")
{
return "succesadmin";
} else
return "succes";
}
}
#SuppressWarnings("null")
public String inscription()
{
LoginService loginService= new LoginServiceImpl();
Login login = loginService.getLogin(getMatricule());
if (login == null){
login.setNom(getNom());
login.setMatricule(getMatricule());
loginService.addLogin(login);
return "inscript";
}
else return "errorinscript";
}
public String listUser(){
return "succeslisteutilisateur";
}
}

Related

Init not being called PrimeFaces

I have an init function in my ManagedBean that is view scoped. But I can't seem to get it to run when the page loads.
Its a private field in this Class
.............
package mike.food;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.JsonMappingException;
#JsonIgnoreProperties(ignoreUnknown = true)
#ManagedBean(name = "nutrition")
#ViewScoped
public class NutritionixResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1016196967087965738L;
private String total_hits;
private String max_score;
private ArrayList<Hits> hits;
private ArrayList<Hits> droppedhits;
public NutritionixResponse() throws JsonParseException, JsonMappingException, IOException {
}
#PostConstruct
public void init() {
this.droppedhits = new ArrayList<Hits>();
}
public String getTotal_hits() {
return total_hits;
}
public void setTotal_hits(String total_hits) {
this.total_hits = total_hits;
}
public String getMax_score() {
return max_score;
}
public void setMax_score(String max_score) {
this.max_score = max_score;
}
public ArrayList<Hits> getHits() {
return hits;
}
public void setHits(ArrayList<Hits> hits) {
this.hits = hits;
}
public ArrayList<Hits> getDroppedhits() {
return droppedhits;
}
public void setDroppedhits(ArrayList<Hits> droppedhits) {
this.droppedhits = droppedhits;
}
}
The main class
#JsonIgnoreProperties(ignoreUnknown = true)
#Manaents Serializable {
gedBean(name = "FoodClient")
#ViewScoped
public class FoodClient implem
/**
* Need to test something
*/
private static final long serialVersionUID = 3874520453001209544L;
private NutritionixResponse nurition;
And the page
<p:outputPanel id="dropArea">
<p:dataTable id="droppedfoodtable" var="food"
value="#{FoodClient.nurition.droppedhits}"

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

JAXB issue-- unexpected element

My JAXB parser suddenly stopped working today. It was working for several weeks. I get the following message. I haven't changed this code for several weeks. Wondering if this set up is good.
EDIT 2: Please could somebody help me! I can't figure this out.
EDIT 1:
My acceptance tests running the same code below are working fine. I believe this is a
classloading issue. I am using the JAXB and StAX in the JDK. However, when I deploy to jboss 5.1, I get the error below. Using 1.6.0_26 (locally) and 1.6.0_30 (dev server). Still puzzling over a solution.
unexpected element (uri:"", local:"lineEquipmentRecord"). Expected
elements are
<{}switchType>,<{}leSwitchId>,<{}nodeAddress>,<{}leId>,<{}telephoneSuffix>,<{}leFormatCode>,<{}groupIdentifier>,<{}telephoneNpa>,<{}telephoneLine>,<{}telephoneNxx>
Here is my unmarshalling class:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class PartialUnmarshaller<T> {
XMLStreamReader reader;
Class<T> clazz;
Unmarshaller unmarshaller;
public PartialUnmarshaller(InputStream stream, Class<T> clazz) throws XMLStreamException, FactoryConfigurationError, JAXBException {
this.clazz = clazz;
this.unmarshaller = JAXBContext.newInstance(clazz).createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
#Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return true;
}
});
this.reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
/* ignore headers */
skipElements(XMLStreamConstants.START_DOCUMENT);
/* ignore root element */
reader.nextTag();
/* if there's no tag, ignore root element's end */
skipElements(XMLStreamConstants.END_ELEMENT);
}
public T next() throws XMLStreamException, JAXBException {
if (!hasNext())
throw new NoSuchElementException();
T value = unmarshaller.unmarshal(reader, clazz).getValue();
skipElements(XMLStreamConstants.CHARACTERS, XMLStreamConstants.END_ELEMENT);
return value;
}
public boolean hasNext() throws XMLStreamException {
return reader.hasNext();
}
public void close() throws XMLStreamException {
reader.close();
}
private void skipElements(Integer... elements) throws XMLStreamException {
int eventType = reader.getEventType();
List<Integer> types = new ArrayList<Integer>(Arrays.asList(elements));
while (types.contains(eventType))
eventType = reader.next();
}
}
This class is used as follows:
List<MyClass> lenList = new ArrayList<MyClass>();
PartialUnmarshaller<MyClass> pu = new PartialUnmarshaller<MyClass>(
is, MyClass.class);
while (pu.hasNext()) {
lenList.add(pu.next());
}
The XML being unmarshalled:
<?xml version="1.0" encoding="UTF-8"?>
<lineEquipment>
<lineEquipmentRecord>
<telephoneNpa>333</telephoneNpa>
<telephoneNxx>333</telephoneNxx>
<telephoneLine>4444</telephoneLine>
<telephoneSuffix>1</telephoneSuffix>
<nodeAddress>xxxx</nodeAddress>
<groupIdentifier>LEN</groupIdentifier>
</lineEquipmentRecord>
<lineEquipmentRecord>
<telephoneNpa>111</telephoneNpa>
<telephoneNxx>111</telephoneNxx>
<telephoneLine>2222</telephoneLine>
<telephoneSuffix>0</telephoneSuffix>
<nodeAddress>xxxx</nodeAddress>
<groupIdentifier>LEN</groupIdentifier>
</lineEquipmentRecord>
</lineEquipment>
Finally, here is MyClass:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This class is used as an envelope to hold Martens
* line equipment information.
* #author spgezf
*
*/
#XmlRootElement(name="lineEquipmentRecord")
public class MyClass {
private String telephoneNpa;
private String telephoneNxx;
private String telephoneLine;
private String telephoneSuffix;
private String nodeAddress;
private String groupIdentifier;
public MyClass(){
}
// Getters and Setters.
#XmlElement(name="telephoneNpa")
public String getTelephoneNpa() {
return telephoneNpa;
}
public void setTelephoneNpa(String telephoneNpa) {
this.telephoneNpa = telephoneNpa;
}
#XmlElement(name="telephoneNxx")
public String getTelephoneNxx() {
return telephoneNxx;
}
public void setTelephoneNxx(String telephoneNxx) {
this.telephoneNxx = telephoneNxx;
}
#XmlElement(name="telephoneLine")
public String getTelephoneLine() {
return telephoneLine;
}
public void setTelephoneLine(String telephoneLine) {
this.telephoneLine = telephoneLine;
}
#XmlElement(name="telephoneSuffix")
public String getTelephoneSuffix() {
return telephoneSuffix;
}
public void setTelephoneSuffix(String telephoneSuffix) {
this.telephoneSuffix = telephoneSuffix;
}
#XmlElement(name="nodeAddress")
public String getNodeAddress() {
return nodeAddress;
}
public void setNodeAddress(String nodeAddress) {
this.nodeAddress = nodeAddress;
}
#XmlElement(name="groupIdentifier")
public String getGroupIdentifier() {
return groupIdentifier;
}
public void setGroupIdentifier(String groupIdentifier) {
this.groupIdentifier = groupIdentifier;
}
}
Thanks, this is classloading issue I couldn't overcome so I abandoned JAXB.
Your PartialUnmarshaller code worked for me. Below is an alternate version that changes the skipElements method that may work better.
import java.io.InputStream;
import java.util.NoSuchElementException;
import javax.xml.bind.*;
import javax.xml.stream.*;
public class PartialUnmarshaller<T> {
XMLStreamReader reader;
Class<T> clazz;
Unmarshaller unmarshaller;
public PartialUnmarshaller(InputStream stream, Class<T> clazz) throws XMLStreamException, FactoryConfigurationError, JAXBException {
this.clazz = clazz;
this.unmarshaller = JAXBContext.newInstance(clazz).createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
#Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return true;
}
});
this.reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
/* ignore headers */
skipElements();
/* ignore root element */
reader.nextTag();
/* if there's no tag, ignore root element's end */
skipElements();
}
public T next() throws XMLStreamException, JAXBException {
if (!hasNext())
throw new NoSuchElementException();
T value = unmarshaller.unmarshal(reader, clazz).getValue();
skipElements();
return value;
}
public boolean hasNext() throws XMLStreamException {
return reader.hasNext();
}
public void close() throws XMLStreamException {
reader.close();
}
private void skipElements() throws XMLStreamException {
while(reader.hasNext() && !reader.isStartElement()) {
reader.next();
}
}
}

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