im new in this page , i'll be concise i had a problem with this code line and i dont what to do . I know this question has been answered but , my problem persist ... i need your help
pd: enclose my code
public class CuentaUsuario implements java.io.Serializable {
private Integer idcuentaUsuario;
private String username;
private String password;
private String correo;
private Date fechaCreacion;
private String creacionUsuario;
private Date fechaModificacion;
private String modificacionUsuario;
private Integer estadoUsuario;
private int idRol;
public CuentaUsuario() {
this.idcuentaUsuario = 0;
}
public CuentaUsuario(String username, String password, Date fechaCreacion, int idRol) {
this.username = username;
this.password = password;
this.fechaCreacion = fechaCreacion;
this.idRol = idRol;
}
public CuentaUsuario(String username, String password, String correo, Date fechaCreacion, String creacionUsuario, Date fechaModificacion, String modificacionUsuario, Integer estadoUsuario, int idRol) {
this.username = username;
this.password = password;
this.correo = correo;
this.fechaCreacion = fechaCreacion;
this.creacionUsuario = creacionUsuario;
this.fechaModificacion = fechaModificacion;
this.modificacionUsuario = modificacionUsuario;
this.estadoUsuario = estadoUsuario;
this.idRol = idRol;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="idcuenta_usuario", unique=true, nullable=false)
public Integer getIdcuentaUsuario() {
return this.idcuentaUsuario;
}
public void setIdcuentaUsuario(Integer idcuentaUsuario) {
this.idcuentaUsuario = idcuentaUsuario;
}
#Column(name="username", nullable=false, length=45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name="password", nullable=false, length=45)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="correo", length=45)
public String getCorreo() {
return this.correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="fecha_creacion", nullable=false, length=19)
public Date getFechaCreacion() {
return this.fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
#Column(name="creacion_usuario", length=45)
public String getCreacionUsuario() {
return this.creacionUsuario;
}
public void setCreacionUsuario(String creacionUsuario) {
this.creacionUsuario = creacionUsuario;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="fecha_modificacion", length=19)
public Date getFechaModificacion() {
return this.fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
#Column(name="modificacion_usuario", length=45)
public String getModificacionUsuario() {
return this.modificacionUsuario;
}
public void setModificacionUsuario(String modificacionUsuario) {
this.modificacionUsuario = modificacionUsuario;
}
#Column(name="estado_usuario")
public Integer getEstadoUsuario() {
return this.estadoUsuario;
}
public void setEstadoUsuario(Integer estadoUsuario) {
this.estadoUsuario = estadoUsuario;
}
#Column(name="id_rol", nullable=false)
public int getIdRol() {
return this.idRol;
}
public void setIdRol(int idRol) {
this.idRol = idRol;
}
}
This is the view
<h:form id ="formCreate">
<p:dialog header="CREACION DE CUENTA" widgetVar="dialogUsuarioCreate"
resizable="false" id="dlgUsuarioCreate"
showEffect="fade" hideEffect="explode" modal="true">
<h:panelGrid id="display" columns="2" cellpadding="4" style="margin:0 auto;">
<h:outputText value="Usuario :" />
<p:inputText value="#{cuentaUsuarioBean.selectedUsuarios.username}"/>
<h:outputText value="Password :" />
<p:inputText value="#{cuentaUsuarioBean.selectedUsuarios.password}"/>
<h:outputText value="Rol :" />
<p:inputText value="#{cuentaUsuarioBean.selectedUsuarios.idRol}"/>
<h:outputText value="Correo :" />
<p:inputText value="#{cuentaUsuarioBean.selectedUsuarios.correo}" size="30"/>
<f:facet name="footer">
<p:separator />
<p:commandButton id="btnCreateAceptar" update=":formDataTable , :msgs"
oncomplete="dialogUsuarioCreate.hide()"
actionListener="#{cuentaUsuarioBean.btnCreateCuenta(actionEvent)}"
icon="ui-icon-disk" title="guardar" value="Guardar" />
<p:commandButton id="btnCreateCancelar"
oncomplete="dialogUsuarioCreate.hide()"
icon="ui-icon-circle-close" title="Cancelar" value="Cancelar" />
</f:facet>
</h:panelGrid>
</p:dialog>
</h:form>
already fixed , thank you for your help but I solved it ! , thank u very much .
Infact you were right ,the problem was the initialize this field ( username ) in the class (cuentaUsuarioBean) i did this look ...
public CuentaUsuarioBean() {
this.usuarios = new ArrayList<CuentaUsuario>();
this.selectedUsuarios = new CuentaUsuario(); /* this is the new line */
}
Related
I have a problem selecting a row from a datatable in PrimeFaces. My selected object in the managed bean is null. For some reason, selected object from the datatable is not setting up correctly the property selectedItinerary in my managed bean.
<p:dataTable id="singleDT" value="#{travellerSearchFlightsManagedBean.searchList}" var="s" selectionMode="single" selection="#{travellerSearchFlightsManagedBean.selectedItinerary}" rowKey="#{s.iden}" >
<f:facet name="header">
Found itineraries
</f:facet>
<p:column headerText="Departure Location">
<h:outputText value="#{s.departureLocation}" />
</p:column>
<p:column headerText="Arrival Location">
<h:outputText value="#{s.arrivalLocation}" />
</p:column>
<p:column headerText="Departure Date">
<h:outputText value="#{s.departureDate}" />
</p:column>
<p:column headerText="Cost">
<h:outputText value="#{s.cost}" />
</p:column>
<p:column headerText="Stops">
<h:outputText value="#{s.stopPrint}" />
</p:column>
<f:facet name="footer">
<p:commandButton process="singleDT" value="Reserve itinerary" action="#{travellerSearchFlightsManagedBean.reserveFlight()}" />
</f:facet>
</p:dataTable>
and the managed bean is like this:
#Named(value = "travellerSearchFlightsManagedBean")
#RequestScoped
public class travellerSearchFlightsManagedBean{
#EJB
private itineraryTravellerFacadeLocal itineraryTravellerFacade;
#EJB
private itineraryFacadeLocal itineraryFacade;
#ManagedProperty(value="#{travellerLoginManagedBean}")
private travellerLoginManagedBean loginBean;
private String departureLocation;
private String arrivalLocation;
private Date departureDate;
private int departureHour;
private int departureMinute;
private int numPassengers;
private int maxStops;
private String economyOrBusiness;
private ArrayList<itineraryDTO> itinerariesList;
private ArrayList<itineraryTraveller> searchList;
private itineraryTraveller selectedItinerary;
private String stopPrint;
private static final Logger LOG = Logger.getLogger(travellerSearchFlightsManagedBean.class.getName());
public String getStopPrint() {
return stopPrint;
}
public travellerLoginManagedBean getLoginBean() {
return loginBean;
}
public void setLoginBean(travellerLoginManagedBean loginBean) {
this.loginBean = loginBean;
}
public void setStopPrint(String stopPrint) {
this.stopPrint = stopPrint;
}
public itineraryTraveller getSelectedItinerary() {
return selectedItinerary;
}
public void setSelectedItinerary(itineraryTraveller selectedItinerary) {
this.selectedItinerary = selectedItinerary;
}
public ArrayList<itineraryTraveller> getSearchList() {
return searchList;
}
public void setSearchList(ArrayList<itineraryTraveller> searchList) {
this.searchList = searchList;
}
public ArrayList<itineraryDTO> getItinerariesList() {
return itinerariesList;
}
public void setItinerariesList(ArrayList<itineraryDTO> itinerariesList) {
this.itinerariesList = itinerariesList;
}
public itineraryFacadeLocal getItineraryFacade() {
return itineraryFacade;
}
public String getEconomyOrBusiness() {
return economyOrBusiness;
}
public void setEconomyOrBusiness(String economyOrBusiness) {
this.economyOrBusiness = economyOrBusiness;
}
public void setItineraryFacade(itineraryFacadeLocal itineraryFacade) {
this.itineraryFacade = itineraryFacade;
}
public String getDepartureLocation() {
return departureLocation;
}
public void setDepartureLocation(String departureLocation) {
this.departureLocation = departureLocation;
}
public String getArrivalLocation() {
return arrivalLocation;
}
public void setArrivalLocation(String arrivalLocation) {
this.arrivalLocation = arrivalLocation;
}
public Date getDepartureDate() {
return departureDate;
}
public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}
public int getDepartureHour() {
return departureHour;
}
public void setDepartureHour(int departureHour) {
this.departureHour = departureHour;
}
public int getDepartureMinute() {
return departureMinute;
}
public void setDepartureMinute(int departureMinute) {
this.departureMinute = departureMinute;
}
public int getNumPassengers() {
return numPassengers;
}
public void setNumPassengers(int numPassengers) {
this.numPassengers = numPassengers;
}
public int getMaxStops() {
return maxStops;
}
public void setMaxStops(int maxStops) {
this.maxStops = maxStops;
}
public travellerSearchFlightsManagedBean() {
}
public void searchFlights(){
try{
int numPassengersEconomy=0;
int numPassengersBusiness=0;
if (economyOrBusiness.equals("Economy")){
numPassengersEconomy=numPassengers;
}else{
numPassengersBusiness=numPassengers;
}
searchList = new ArrayList<itineraryTraveller>();
itinerariesList= new ArrayList<itineraryDTO>();
int id=itineraryFacade.findItineraries(itinerariesList,departureLocation, arrivalLocation,departureDate,numPassengersEconomy, numPassengersBusiness);
searchList=itineraryFacade.listItineraries(maxStops,itinerariesList,arrivalLocation, departureLocation, numPassengersEconomy, numPassengersBusiness);
} catch(NullPointerException e) {}
}
public void reserveFlight(){
//if (){
try{
//status reserved when traveller reserves an itinerary
selectedItinerary.setStatus('r');
//set the userName from the user who reserved this itinerary before persist it in a shared among all users db
//persist the reserved itinerary in the db
itineraryTravellerFacade.create(selectedItinerary);
} catch(NullPointerException e) {}
}
}
I'm trying to delete one cell with a <p:commandButton> and after i click i want to update my table. But all what happens is, that i got this Exception.
javax.persistence.EntityNotFoundException: Unable to find de.test.Datei with id 5
But in my Database i can see the facts in each table. Also when i click the button, the dates will be delete correctly. But my table doesn't update, so the cell isn't disappeared. And when i click twice, i got the above error message.
Datei.class
#Entity
public class Datei implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "DATA_ID_GENERATOR", sequenceName = "SEQ_DATA", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DATA_ID_GENERATOR")
private long id;
private String name;
private long groesse;
#Temporal(TemporalType.TIMESTAMP)
private Date datum;
#Basic(fetch = FetchType.LAZY)
#Lob
private byte[] datei;
#ManyToOne
private Benutzer benutzer;
public Benutzer getBenutzer() {
return benutzer;
}
public void setBenutzer(Benutzer benutzer) {
this.benutzer = benutzer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getGroesse() {
return groesse;
}
public void setGroesse(long groesse) {
this.groesse = groesse;
}
public byte[] getDatei() {
return datei;
}
public void setDatei(byte[] datei) {
this.datei = datei;
}
public Datei() {
// TODO Auto-generated constructor stub
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
#Override
public String toString() {
return "Datei [id=" + id + ", name=" + name + ", groesse=" + groesse
+ ", datum=" + datum + ", datei=" + Arrays.toString(datei)
+ "]";
}
}
Benutzer.class
#Entity
public class Benutzer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "CUSTOMER_ID_GENERATOR", sequenceName = "SEQ_CUSTOMER", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUSTOMER_ID_GENERATOR")
private long id;
private String name;
private String email;
private long kundennummer;
#OneToMany(mappedBy = "benutzer", orphanRemoval = true)
private List<Datei> datei;
#Override
public String toString() {
return "Benutzer [id=" + id + ", name=" + name + ", email=" + email
+ ", kundennummer=" + kundennummer + ", datei=" + datei + "]";
}
public List<Datei> getDatei() {
return datei;
}
public void setDatei(List<Datei> datei) {
this.datei = datei;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getKundennummer() {
return kundennummer;
}
public void setKundennummer(long kundennummer) {
this.kundennummer = kundennummer;
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
}
My DateiDAO.class
[...]
public void loeschen(Datei datei, Benutzer benutzer) {
EntityManager em = emf.createEntityManager();
EntityTransaction tr = em.getTransaction();
tr.begin();
benutzer = em.merge(benutzer);
datei = em.merge(datei);
tr.commit();
benutzer.getDatei().remove(datei);
tr.begin();
em.merge(benutzer);
em.remove(em.merge(datei));
tr.commit();
}
So the only problem is, that my table dosen't update.
If i use richfaces, it works fine.
main.xhtml
<h:form id="myForm">
<p:dataTable id="dateien" var="data"
value="#{mainController.ben.datei}" rowKey="#{data.id}"
selectionMode="single" rows="5" paginator="true" rowsPerPageTemplate="5,10,15" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}">
<f:facet name="header">
<h:outputText value="Uploaded"/>
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{data.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{data.name}" />
</p:column>
<p:column headerText="Datum">
<h:outputText value="#{data.datum}" />
</p:column>
<p:column headerText="Delete">
<p:commandButton update="myForm"
actionListener="#{mainController.loeschen(data)}"
icon="ui-icon-trash" />
</p:column>
</p:dataTable>
</h:form>
Miss it in your process:
Delete this item from your mainController.ben.datei list after you delete item from database, and update your dataTable like Ouerghi Yassine told.
or
Get load again your data list from database on loeschen method after you delete item, its more security if you do this system and wish no have a concurrence problem.
So, you provide to your dataTable one list binding with your bean, in your case the datei list, so even if you delete item from database, this item cant be this list too.
I'm sorry for my english.
Add update="dateien" to your commandButton
<p:commandButton update="myForm"
actionListener="#{mainController.loeschen(data)}"
icon="ui-icon-trash"
update="dateien"/>
This question already has answers here:
Showing Hibernate/JPA results in JSF datatable causes: java.lang.NumberFormatException: For input string: "[propertyname]"
(2 answers)
Closed 7 years ago.
public List<MemberEntity> getMember() {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("PrimeEclipseLink");
EntityManager entityManager = entityManagerFactory
.createEntityManager();
Query query = entityManager
.createNativeQuery("Select * FROM member");
memberEntities = (List<MemberEntity>)query.getResultList();
return memberEntities;
}
I want to fill my databable from database.but it doesnt work please help me:) when I click list button the table fill like picture.by the way,my database contains 3 records.thats why 3 zero.
xhtml page is here.
<h:form id="member">
<p:dataTable var="members" value="#{mainScreen.memberEntities}">
<p:column headerText="name">
<h:outputText value="#{memberEntity.name}" />
</p:column>
<p:column headerText="surname">
<h:outputText value="#{memberEntity.surname}" />
</p:column>
<p:column headerText="fathername">
<h:outputText value="#{memberEntity.fathername}" />
</p:column>
<p:column headerText="age">
<h:outputText value="#{memberEntity.age}" />
</p:column>
<p:column headerText="email">
<h:outputText value="#{memberEntity.email}" />
</p:column>
<p:column headerText="username">
<h:outputText value="#{memberEntity.username}" />
</p:column>
<p:column headerText="password">
<h:outputText value="#{memberEntity.password}" />
</p:column>
</p:dataTable>
</h:form>
` #ManagedBean
#Entity
#Table(name = "member")
public class MemberEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int memberid;
private int age;
private String name;
private String surname;
private String fathername;
private String email;
private String username;
private String password;
public MemberEntity(int memberid, int age, String name, String surname,
String fathername, String email, String username, String password) {
super();
this.memberid = memberid;
this.age = age;
this.name = name;
this.surname = surname;
this.fathername = fathername;
this.email = email;
this.username = username;
this.password = password;
}
public MemberEntity() {
super();
// TODO Auto-generated constructor stub
}
public int getMemberid() {
return memberid;
}
public void setMemberid(int memberid) {
this.memberid = memberid;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getFathername() {
return fathername;
}
public void setFathername(String fathername) {
this.fathername = fathername;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}
#Override
public String toString() {
return "Member [memberid=" + memberid + ",name=" + name + ",surname="
+ surname + ",age=" + age + ",email=" + email + ",fathername="
+ fathername + ",username=" + username + ",password="
+ password + "]";
}
}
In your p:dataTable the var attribute is named membres, while in the p:column values you are using memberEntity, so you have to change it to members.
From:
<p:column headerText="name">
<h:outputText value="#{memberEntity.name}" />
</p:column>
To:
<p:column headerText="name">
<h:outputText value="#{members.name}" />
</p:column>
I found solution. in getMember() method instead of createNativeQuery("Select * FROM member") true---> createNativeQuery("Select * FROM members,MemberEntity.class)
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 have a problem with my managedbeans. I cannot manage to pass parameters between them. Here is an XHTML snippet. It is basically a form for login. It just sends the parameters to back bean.
<h:outputLabel for="username" value="Kullanıcı Adı: *" />
<p:inputText id="username" value="#{loginBean.username}" required="true" requiredMessage="Kullanıcı adı giriniz.">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="username" display="icon"/>
<h:outputLabel for="password" value="Şifre: *" />
<p:inputText id="password" value="#{loginBean.password}" required="true" requiredMessage="Şifreyi giriniz!" type="password">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="password" id="msgPass" display="icon"/>
<f:facet name="footer">
<center>
<p:commandButton id="submit" value="Giriş" icon="ui-icon-check" action="#{loginBean.check}" style="margin:0" update="grid"/>
</center>
</f:facet>
In my backing bean, I am checking whether the user input matches with the database record. If so then I let him enter the system. At the same time, I am taking his full name.
My backbean:
#ManagedBean
#RequestScoped
public class LoginBean {
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 getMgs() {
return mgs;
}
public void setMgs(String mgs) {
this.mgs = mgs;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getOriginalURL() {
return originalURL;
}
public void setOriginalURL(String originalURL) {
this.originalURL = originalURL;
}
private String username;
private String password;
private String mgs;
private String fullname;
private String originalURL;
private static Logger log = Logger.getLogger(LoginBean.class.getName());
public String check() throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/projetakip", "root", "");
Statement stmt = con.createStatement();
String md5Pass = md5(password);
String SQL = "select * from users where username='" + username + "' and password='" + md5Pass + "'";
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
if (username.matches(rs.getString("username")) && md5Pass.matches(rs.getString("password"))) {
this.fullname = rs.getString("ad") + " " + rs.getString("soyad");
return "panel?faces-redirect=true";
} else {
FacesMessage msg = new FacesMessage("Yanlış kullanıcı adı/şifre.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "index?faces-redirect=true";
}
}
return "index?faces-redirect=true";
}
public void getProductSetupData(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
Data data = context.getApplication().evaluateExpressionGet(context, "#{data}", Data.class);
}
What I want is to pass fullName to other beans (or pages). How can I pass this variable between my beans?
Thanks in advance.
BalusC wrote a whole blog post about communication in JSF 2.0, it is truly worthy of your time. Reading it, you will discover that there are more than one way of doing it, one of them being injecting the property itself, in your other beans:
#ManagedProperty("#{loginBean.fullName}")
private String fullName;
And another, perhaps more appropriate, could be to inject the bean itself:
#ManagedProperty("#{loginBean}")
private LoginBean loginBean;