I am new to Java Server Faces. I am doing one simple login jsf application which has layout.xhtml, login.xhtml, loginbean.java, changepassword.xhtml, changepasswordbean.java. Login functions are working fine but changepassword function is causing some problem which I can't find what's the reason for error. I am getting error when clicking Clear Button in changepassword.xhtml page. If I click changepassword button a Null pointer exception have occured because I am trying to get a value(companyid) from another loginbean to changepasswordbean. After clicking back button in browser then selecting changepassword menu I am getting a error like Parent was not null, but this component not related. Sometimes menus will not be displayed. I don't know what's the problem, so any help here.
LoginBean.java
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable
{
Logger log;
#ManagedProperty(value = "loginBean")
public boolean isLoggedin;
public String username;
public String password;
public String companyid;
public boolean notloggedin;
#ManagedProperty(value = "#{tabMenu}")
private TabMenu tabMenu;
public LoginBean()
{
log=LoggerFactory.getLogger(LoginBean.class);
}
public void clear()
{
setUsername(null);
setPassword(null);
setCompanyId(null);
}
public String login()
{
setIsLoggedin(true);
setNotLoggedIn(false);
setCompanyId("companyid_1");
tabMenu.setTabMenu();
return "home";
}
public String logout()
{
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
setIsLoggedin(false);
setNotLoggedIn(true);
return "/login.xhtml?faces-redirect=true";
}
public void setUsername(String username)
{
this.username=username;
}
public String getUsername()
{
return username;
}
public void setPassword(String password)
{
this.password=password;
}
public String getPassword()
{
return password;
}
public void setIsLoggedin(boolean isloggedin)
{
this.isLoggedin=isloggedin;
}
public boolean getIsLoggedin()
{
return isLoggedin;
}
public void setNotLoggedIn(boolean notloggedin)
{
this.notloggedin=notloggedin;
}
public boolean getNotLoggedIn()
{
if(getIsLoggedin())
{
this.notloggedin=false;
}
else
this.notloggedin=true;
return notloggedin;
}
public void setCompanyId(String companyid)
{
this.companyid=companyid;
}
public String getCompanyId()
{
return companyid;
}
public TabMenu getTabMenu()
{
return tabMenu;
}
public void setTabMenu(TabMenu tabMenu)
{
this.tabMenu = tabMenu;
}
}
ChangePasswordBean.java
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedBean
#RequestScoped
public class ChangePasswordBean implements Serializable
{
Logger log;
#ManagedProperty(value = "changePasswordBean")
public String oldPassword;
public String newPassword;
public String retypePassword;
#ManagedProperty(value = "#{loginBean}")
public LoginBean lbean;
public ChangePasswordBean()
{
log=LoggerFactory.getLogger(ChangePasswordBean.class);
}
public void changePassword()
{
log.debug("Company Id: "+lbean.getCompanyId());
log.debug("User Name: "+lbean.getUsername());
boolean flag=false;
ChangePasswordDAO changepass=new ChangePasswordDAO();
if(oldPassword!=null && newPassword!=null && retypePassword!=null)
{
if(newPassword.equals(retypePassword))
{
flag=changepass.changePassword(oldPassword, newPassword,lbean.getUsername(),lbean.getCompanyId());
if(flag)
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_INFO,"Info", "Password Changed Successfully"));
}
else
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Password Not Changed"));
}
}
else
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "New Password and Retype Password didn't match"));
}
}
else
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", "Old Password/New Password/Retype Password Should not be empty"));
}
}
public void clear()
{
setOldPassword(null);
setNewPassword(null);
setRetypePassword(null);
}
public void setOldPassword(String oldPassword)
{
this.oldPassword=oldPassword;
}
public String getOldPassword()
{
return oldPassword;
}
public void setNewPassword(String newPassword)
{
this.newPassword=newPassword;
}
public String getNewPassword()
{
return newPassword;
}
public void setRetypePassword(String retypePassword)
{
this.retypePassword=retypePassword;
}
public String getRetypePassword()
{
return retypePassword;
}
public void setLbean(LoginBean lbean)
{
this.lbean=lbean;
}
public LoginBean getLbean()
{
return lbean;
}
}
changepassword.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<body>
<ui:composition template="../templates/layout.xhtml">
<ui:define name="content">
<h:form id="changepassform" rendered="#{loginBean.isLoggedin}">
<p:messages id="messages" autoUpdate="true" redisplay="false"
showDetail="true"/>
<h:panelGrid columns="2">
<h:outputLabel value="Current Password"/>
<p:inputText value="#{changePasswordBean.oldPassword}" style="width: 106px;"/>
<h:outputLabel value="New Password"/>
<p:password value="#{changePasswordBean.newPassword}" style="width: 106px;"></p:password>
<h:outputLabel value="Retype New Password"/>
<p:inputText value="#{changePasswordBean.retypePassword}" style="width: 106px;"/>
</h:panelGrid>
<br></br>
<h:panelGrid columns="2" style="margin-left: 100px">
<h:commandButton action="#{changePasswordBean.changePassword()}" value="Change Password" id="btnchange" />
<h:commandButton action="#{changePasswordBean.clear()}" value="Clear" id="btnclear" />
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
I solved this issue by setting the transient option=true. Because I was creating menus dynamically which resulted in "WARNING: Unable to save dynamic action with clientId 'j_idt8:j_idt9:0:j_id3' because the UIComponent cannot be found" and "Cannot remove the same component twice: j_idt8:j_idt9:j_id3" problems.
public void setMenus(String type)
{
MenuItem item;
item=new MenuItem();
item.setValue("Change Password");
item.setStyle("color:black");
item.setTransient(true); /* Set this to solve the problem */
item.setUrl("/adminAccount/changepassword.xhtml");
submenus.addMenuItem(item);
}
Related
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
I can not pass values from my login form to backing bean to authenticate user by apache shiro in my web app. Does anybody know why?
shiro.ini
[main]
authc.loginUrl = /login.jsf
authc.successUrl = /pages/welcome.jsf
[users]
admin = 1234
[urls]
/login.jsf = authc
/pages/** = authc
login.xhtml
<ui:define name="content">
<div id="login_form">
<h:form prependId="false">
<center>
<h1>Sign in <p:link value="or create an account" outcome="registration" style="color: #0A9CE5; text-decoration: none;" /></h1>
<table>
<tr>
<td><p:inputText id="username" value="#{shiroLoginBean.username}" placeholder="Login" required="true" /></td>
</tr>
<tr>
<td><p:password id="password" value="#{shiroLoginBean.password}" placeholder="Password" required="true" /></td>
</tr>
</table>
</center>
<p:commandButton value="Sign in" action="#{shiroLoginBean.doLogin}" />
</h:form>
</div>
BEAN:
package utils.security;
import java.io.IOException;
import java.io.Serializable;
import javax.ejb.Stateless;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Named("shiroLoginBean")
#Stateless
#ViewScoped
public class ShiroLoginBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(ShiroLoginBean.class);
private String username;
private String password;
public ShiroLoginBean() {
}
/**
* Try and authenticate user.
*/
public void doLogin() {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword());
try {
subject.login(token);
FacesContext.getCurrentInstance().getExternalContext().redirect("pages/welcome.jsf");
} catch (UnknownAccountException ex) {
log.error(ex.getMessage(), ex);
} catch (IncorrectCredentialsException ex) {
log.error(ex.getMessage(), ex);
} catch (LockedAccountException ex) {
log.error(ex.getMessage(), ex);
} catch (AuthenticationException | IOException ex) {
log.error(ex.getMessage(), ex);
} finally {
token.clear();
}
}
//~ Setters and Getters
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Problem is on this row...
UsernamePasswordToken token = new UsernamePasswordToken(getUsername(), getPassword());
... getUsername and getPassword is always null. Thank you so much for answer!!
Your #ViewScoped import is wrong - since you use #Named (meaning its a CDI bean) you should use
import javax.faces.view.ViewScoped;
Since you omitted a relevant scope you'll get #Dependent scope, which I've never seen the use for but its very short lived (inputs will be bound to one bean, but when doLogin() runs it will be in a new one).
This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
I got this error below when I was running my JSF page.
javax.el.PropertyNotFoundException: Target Unreachable, 'null' returned null..
Warning: /createStaff.xhtml #33,125
value="#{staffBean.staff.firstName}": Target Unreachable, 'null'
returned null javax.el.PropertyNotFoundException: /createStaff.xhtml
#33,125 value="#{staffBean.staff.firstName}": Target Unreachable,
'null' returned null
I don't get why I will run into the error when I use value="#{staffBean.staff.firstName}". There is no problem when I use the value="#{staffBean.userName}" and value="#{staffBean.passWord}" above.
This is my createStaff.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Create Staff</title>
</h:head>
<h:body>
<f:view>
<h:form>
<p:panel id ="panel" header="Staff Creation">
<p:messages id="msgs" />
<h:panelGrid columns="3" columnClasses="label, value">
<h:outputText value="Username: *" />
<p:inputText id="username" value="#{staffBean.userName}" required="true" label="Username">
</p:inputText>
<p:message for="username" />
<h:outputLabel for="pwd1" value="Password 1: *" />
<p:password id="pwd1" value="#{staffBean.passWord}" match="pwd2" label="Password 1" required="true" feedback="true" />
<p:message for="pwd1" />
<h:outputLabel for="pwd2" value="Password 2: *" />
<p:password id="pwd2" value="#{staffBean.passWord}" label="Password 2" required="true" feedback="true" />
<p:message for="pwd2" />
<h:outputText value="First name: *" />
<p:inputText id="firstname" value="#{staffBean.staff.firstName}" required="true" label="Username">
</p:inputText>
<p:message for="firstname" />
<h:outputText value="Last name: *" />
<p:inputText id="lastname" value="#{staffBean.staff.lastName}" required="true" label="Username">
</p:inputText>
<p:message for="lastname" />
<h:outputText value="Last name: *" />
<p:selectOneRadio id="genderconsole" value="#{staffBean.staff.gender}" required="true">
<f:selectItem itemLabel="Male" itemValue="Male" />
<f:selectItem itemLabel="Female" itemValue="Female" />
</p:selectOneRadio>
<p:message for="genderconsole" />
<p:commandButton value="Create Staff"
id="ajax"
update="panel">
</p:commandButton>
</h:panelGrid>
</p:panel>
</h:form>
</f:view>
</h:body>
</html>
This is my StaffBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package managedbean;
import entities.Staff;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import sessionBean.staffSessionBeanLocal;
#Named(value = "staffBean")
#SessionScoped
//#ViewScoped
public class StaffBean implements Serializable {
#EJB
private staffSessionBeanLocal staffSession;
private String userName;
private String passWord;
private String loginStatus;
private Staff staff;
...........
////Code removed
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getLoginStatus() {
return loginStatus;
}
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
}
This is my staff entity.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Staff extends User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String imageURL;
#ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private List<Roles> roles = new ArrayList<Roles>();
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Staff)) {
return false;
}
Staff other = (Staff) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Staff[ id=" + id + " ]";
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
}
This is my User class which Staff class extends from.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String password;
private Timestamp joinDate;
private String userType;
private String gender;
private String email;
private String contactNo;
private String firstName;
private String lastName;
private Timestamp dOB;
private String address;
private String accountStatus;
private int numOfFailLogin;
private String maritalStatus;
private String activationCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.User[ id=" + id + " ]";
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Timestamp getJoinDate() {
return joinDate;
}
public void setJoinDate(Timestamp joinDate) {
this.joinDate = joinDate;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Timestamp getdOB() {
return dOB;
}
public void setdOB(Timestamp dOB) {
this.dOB = dOB;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccountStatus() {
return accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public int getNumOfFailLogin() {
return numOfFailLogin;
}
public void setNumOfFailLogin(int numOfFailLogin) {
this.numOfFailLogin = numOfFailLogin;
}
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
}
You have no property firstName in your entity staff
UPDATE:
Looks like your staffobject is null add:
#PostConstruct
public void init() {
staff = new Stuff();
}
The error suggests that when the "firstName" is being accessed, it cannot be reached. So the "Staff" has not been constructed yet.
Add a method to your managed bean, this will resolve the issue.
#PostConstruct
public void init() {
staff= new Staff ();
}
For better understanding of why you should do it that way and not
Staff staff = new Staff();
JSF - what is the difference between #PostConstruct and direct method call from constructor?
I've asked one thousand of times but no one gives me a valid solution. Please why in my xhtml page the post construct is called all times when i press the button?how can i solve this problem?Please a valid solution. I've read many answers but they don't fit with my problem.I'm in trouble by 1 week.
The scope of my xhtml isn't changed :
update of a render component that updates another component
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Add a Default Package</title>
</h:head>
<h:body>
<h:form id="form">
<p:outputLabel for="Name">Name:</p:outputLabel>
<p:inputText id="Name"
value="#{addDefaultPackageBean.defpackDTO.name}" />
<p:message for="Name" />
<p:outputLabel for="Location">Locations Available:</p:outputLabel>
<p:selectOneMenu id="Location"
value="#{addDefaultPackageBean.defpackDTO.location}">
<f:selectItems
value="#{addDefaultPackageBean.availableLocations}" />
</p:selectOneMenu>
<p:commandButton action="#{addDefaultPackageBean.Search()}" value="Ciao" render=":form:Volo" update=":form:Volo :form"></p:commandButton>
<p:panel header="Voli Disponibili per la location selezionata"
id="Volo" rendered="#{addDefaultPackageBean.flag}">
<h:panelGrid columns="3" id="voloGrid">
<p:outputLabel for="Volare">Volo:</p:outputLabel>
<p:selectOneMenu for="Volare" value="#{addDefaultPackageBean.fly}">
<f:selectItems id="Volare" value="#{addDefaultPackageBean.elelisfly}"
var="Ciao" itemValue="#{Ciao.name}"
itemLabel="#{Ciao.name}" />
</p:selectOneMenu>
<p:commandButton actionListener="#{addDefaultPackageBean.sel()}" value="hotel and escursions" render="#form" update=":form:Hotel :form"/>
</h:panelGrid>
</p:panel>
<p:outputLabel for="Hotel">Hotel:</p:outputLabel>
<p:selectOneMenu for="Hotel" value="#{addDefaultPackageBean.hotel}">
<f:selectItems id="Hotel"
value="#{addDefaultPackageBean.elelishotel}" var="ElementDTO"
itemValue="#{ElementDTO.name}" itemLabel="#{ElementDTO.name}" />
</p:selectOneMenu>
<p:message for="Hotel" />
<p:commandButton actionListener="#{addDefaultPackageBean.add}" value="Add" update=":form:Volo :form:Hotel" render="#form" process="#this,:form:Volo,:form:Location"/>
</h:form>
</h:body>
</html>
My bean page:
package beans;
import java.awt.Event;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.view.ViewScoped;
import elementManagement.ElementMgr;
import elementManagementDTO.ElementDTO;
import DefaultPackageManagement.DefaultPackageMgr;
import DefaultPackageManagementDTO.DefaultPackageDTO;
#ManagedBean(name="addDefaultPackageBean") //come viene richiamato
#ViewScoped
public class AddDefaultPackageBean implements Serializable {
/**
*
*/
#EJB
private DefaultPackageMgr defpackMgr;
private DefaultPackageDTO defpackDTO;
private ArrayList<ElementDTO> elelisfly;
private ArrayList<ElementDTO> elelishotel;
private ArrayList<ElementDTO> elelisescursion;
private ArrayList<ElementDTO> elelis;
private ElementDTO[] selectedEscursions;
private String fly;
private String hotel;
private Boolean flag=true;
private Boolean flagdopo=true;
private ArrayList<String> availableLocations;
private ElementDTO flyElem;
#EJB
private ElementMgr elemMgr;
public ElementDTO[] getSelectedEscursions() {
return selectedEscursions;
}
public void setSelectedEscursions(ElementDTO[] selectedEscursions) {
this.selectedEscursions = selectedEscursions;
}
public AddDefaultPackageBean() {
defpackDTO = new DefaultPackageDTO();
this.elelishotel=new ArrayList<ElementDTO>();
this.elelisescursion=new ArrayList<ElementDTO>();
this.elelisfly=new ArrayList<ElementDTO>();
this.availableLocations=new ArrayList<String>();
this.flyElem=new ElementDTO();
}
#PostConstruct
public void init()
{
System.out.print("merda init ");
if(this.getElelisfly().size()==0){System.out.print("Voli vuoto ");}
this.setElelis(elemMgr.getAllElements());
this.selectedEscursions=new ElementDTO[this.getElelis().size()];
this.fly="";
for(ElementDTO e:elelis)
{
if (this.availableLocations.contains(e.getLocation())==false)
{
this.availableLocations.add(e.getLocation());
}
}
}
public String add() {
System.out.print("entrato nell'ultimo step!il mio hotel è "+hotel);
//System.out.print("entrato nell'ultimo step!il mio hotel è "+this.selectedEscursions[0].getName());
/* //assegno location al pacchetto defpackDTO
this.defpackDTO.setLocation(this.getFlyElem().getLocation());
//assegno location a defpackDTO
this.defpackDTO.getElem().add(this.getFlyElem());
//assegno hotel a defpackDTO
this.AssignElemHotelFromSelection();
//assegno escursioni a defpackDTO
for(int i=0;i<this.selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(this.selectedEscursions[i]);
}
defpackMgr.save(defpackDTO);
*/
return "/employee/index?faces-redirect=true";
}
public void sel()
{
System.out.print("ehila"+this.fly );
this.setElelis(this.elemMgr.getAllElementsByLocation(this.defpackDTO.getLocation()));
for(ElementDTO e:elelis)
{
System.out.print("elemento della location Haiti "+e.getName());
}
for(ElementDTO e:elelis)
{
System.out.print("elementisfwefsf dei voli "+e.getName());
}
this.AssignElemFlyFromSelection();
System.out.print(this.fly+"Il volo selezionato per la location è "+this.getFlyElem().getName() );
this.elelisescursion.clear();
this.elelishotel.clear();
for(ElementDTO e:elelis)
{
if(e.getType().equals("Hotel"))
{
System.out.print("ho un hotel tra gli elementi "+e.getName() );
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&((e.getEndingDate().before(this.flyElem.getEndingDate()))))
{
System.out.print("ho un hotel tra gli elementi con le date giuste"+e.getName());
this.getElelishotel().add(e);
}
}
else
{
if(e.getType().equals("Escursion"))
{
if(e.getStartingDate().after(this.flyElem.getStartingDate())&&(e.getEndingDate().before(this.flyElem.getEndingDate())))
{
System.out.print("ho un escursione tra gli elementi con le date giuste"+e.getName());
this.getElelisescursion().add(e);
}
}
}
}
this.setFlag(true);
this.setFlagdopo(true);
}
public DefaultPackageDTO getDefpackDTO() {
return defpackDTO;
}
public void setDefpackDTO(DefaultPackageDTO defpackDTO) {
this.defpackDTO = defpackDTO;
}
public ArrayList<ElementDTO> getElelisfly() {
return elelisfly;
}
public void setElelisfly(ArrayList<ElementDTO> elelisfly) {
this.elelisfly = elelisfly;
}
public ArrayList<ElementDTO> getElelishotel() {
return elelishotel;
}
public void setElelishotel(ArrayList<ElementDTO> elelishotel) {
this.elelishotel = elelishotel;
}
public ArrayList<ElementDTO> getElelisescursion() {
return elelisescursion;
}
public void setElelisescursion(ArrayList<ElementDTO> elelisescursion) {
this.elelisescursion = elelisescursion;
}
public String getFly() {
return fly;
}
public void setFly(String fly) {
this.fly = fly;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
private void AssignElemFlyFromSelection()
{
for (ElementDTO elem:this.elelisfly)
{
if(elem.getName().equals(this.fly))
{
this.flyElem=elem;
}
}
}
private void AssignElemHotelFromSelection()
{
for (ElementDTO elem:this.elelishotel)
{
if(elem.getName().equals(this.hotel))
{
this.defpackDTO.getElem().add(elem);
}
}
}
private void AssignElemEscursionFromSelection()
{
for(int i=0;i<selectedEscursions.length;i++)
{
this.defpackDTO.getElem().add(selectedEscursions[i]);
}
}
public void Search(){
this.getElelisfly().clear();
String s=defpackDTO.getLocation();
System.out.print("luogo scelto "+s);
this.setElelis(this.elemMgr.getAllElementsByLocation(s));
for(ElementDTO e:elelis)
{
System.out.print("aggiungo volo "+e.getName());
if(e.getType().equals("Flight"))
{
this.getElelisfly().add(e);
System.out.print("aggiungo volo "+e.getName());
}
}
this.setFlag(true);
}
public ArrayList<ElementDTO> getElelis() {
return elelis;
}
public void setElelis(ArrayList<ElementDTO> elelis) {
this.elelis = elelis;
}
public ArrayList<String> getAvailableLocations() {
return availableLocations;
}
public void setAvailableLocations(ArrayList<String> availableLocations) {
this.availableLocations = availableLocations;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public boolean isFlagdopo() {
return flagdopo;
}
public void setFlagdopo(boolean flagdopo) {
this.flagdopo = flagdopo;
}
public ElementDTO getFlyElem() {
return flyElem;
}
public void setFlyElem(ElementDTO flyElem) {
this.flyElem = flyElem;
}
}
Use import javax.faces.bean.ViewScoped; if the managed bean is not a CDI artifact.
How to implement a simple add/remove dynamic <rich:tabPanel>?
(I've seen people asking this around so I thought postin a Q&A of a simple implementation)
The implementation has 3 custom classes:
Content: contains the values to be displayed in a tab;
ItemTab: contais an UITab object and a Content object;
MyTabs: EJB managed bean that provides access to the tabs and adding/removal methods.
The code is:
Content:
public class Content {
String name;
String job;
String dept;
public Content() {
name = "John Doe";
job = "None";
dept = "None";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
TabItem:
public class TabItem {
UITab component;
Content content;
public TabItem() {
component = new UITab();
content = new Content();
}
public UITab getComponent() {
return component;
}
public void setComponent(UITab tab) {
this.component = tab;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
}
MyTabs:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class MyTabs implements Serializable {
private List<TabItem> tabs;
public MyTabs() {
tabs = new ArrayList<TabItem>();
}
#PostConstruct
private void init() {
createTab();
createTab();
createTab();
}
public void createTab() {
TabItem tab = new TabItem();
tab.getComponent().setId("Tab" + (tabs.size()+1));
tab.getComponent().setHeader("Tab " + (tabs.size()+1));
tab.getContent().setName("John Doe " + (tabs.size()+1));
tab.getContent().setJob("Salesman " + (tabs.size()+1));
tab.getContent().setDept("Sales " + (tabs.size()+1));
tabs.add(tab);
}
public void removeTab(TabItem tab) {
tabs.remove(tab);
}
public List<TabItem> getTabs() {
return tabs;
}
public void setTabs(List<TabItem> tabs) {
this.tabs = tabs;
}
}
tabview.xhtml:
<h:commandLink value="Add Tab"
actionListener="#{myTabs.createTab()}"/>
<rich:tabPanel switchType="client">
<c:forEach items="#{myTabs.tabs}" var="tab">
<rich:tab value="#{tab.component}">
<f:facet name="header">
<h:outputLabel value="#{tab.component.header}"/>
<h:commandLink value=" X" actionListener="#{myTabs.removeTab(tab)}"/>
</f:facet>
<h:panelGrid columns="2">
<h:outputLabel value="Name: "/>
<h:outputLabel value="#{tab.content.name}"/>
<h:outputLabel value="Dept: "/>
<h:outputLabel value="#{tab.content.dept}"/>
<h:outputLabel value="Job: "/>
<h:outputLabel value="#{tab.content.job}"/>
</h:panelGrid>
</rich:tab>
</c:forEach>
</rich:tabPanel>