jsf set errors when i connected to workbench - jsf

I'm new to java ee and I'm trying to make my first website using java ee but I find a lot of difficult when i want to connect my jsf to workbench I have also a problem with serialization because i have always to generate the serial of beans manually
this it my beans
Userbean.java
#ManagedBean
#Named /*("userBean")*/
#RequestScoped
public class Userbean implements Serializable{
private static final long serialVersionUID = 1043069413653729199L;
private String iduser="";
private String username="name";
private String password="0000";
private String email="";
private String city="";
private String country="";
public Userbean() {
super();
// TODO Auto-generated constructor stub
}
public Userbean(String iduser, String username, String password, String email, String city, String country) {
super();
this.iduser = iduser;
this.username = username;
this.password = password;
this.email = email;
this.city = city;
this.country = country;
}
public String getIduser() {
return iduser;
}
public void setIduser(String iduser) {
this.iduser = iduser;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String returnAction2() {
PreparedStatement ps;
String query ="INSERT INTO `jee`.`user`( `username`, `email`, `password`, `city`, `country`) VALUES (?,?,?,?,?)";
boolean a=false;
try {
ps= Myconnection.getConnection().prepareStatement(query);
ps.setString(1,username);
ps.setString(2,email);
ps.setString(3,password);
ps.setString(4,city);
ps.setString(5,country);
if(ps.executeUpdate()>0){
a=true;
}
} catch (SQLException ex) {
ex.getStackTrace();
a=false;
}
return a==true ? "success" : "failure";
}
}
this is my view sign up
<!DOCTYPE html>
<html xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<f:view>
<head>
<title>Login screen</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<h1>sign up</h1>
<h:form>
username:
<h:inputText id="username" value="#{userBean.username}" />
<br/>
Password:
<h:inputSecret id="password1" value="#{userBean.password}" />
<br/>
email:
<h:inputSecret id="email" value="#{userBean.email}" />
<br/>
city:
<h:inputSecret id="city" value="#{userBean.city}" />
<br/>
country:
<h:inputSecret id="country" value="#{userBean.country}" />
<br/>
<h:commandButton action="#{userBean.returnAction2}" value="Connect" />
</h:form>
</body>
</f:view>
</html>

Related

JSF EL Expressions and Java beans

I have a JSF project and I am trying to create a login page, I have managed to get the username and password from the database and validate them, my project has a Java bean, managed bean and DAO classes, when the user successfully logs in, I would like to print Hello Mr.
< h:outputLabel value="#{mBLogin.user.firstName}" /> the Hello Mr. is printing but the name is not, although when testing my DAO class I'm printing the name to the console without any problem! Can someone advice what I am doing wrong?
My managed bean class:
#ManagedBean
#SessionScoped
public class MBLogin {
User user = new User();
LoginDAO loginDao = new LoginDAO();
public String validteStudent() {
boolean valid = loginDao.validateStudent(user.getUserId(), user.getPassword());
if (valid) {
user.getFirstName();
HttpSession session = SessionUtils.getSession();
session.setAttribute("username", user);
return "admin";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Passowrd", "Please enter correct username and Password"));
return "login";
}
}
public void setUser(User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
My Java Bean class:
#Table(name = "students_info")
public class User {
#Column(name = "std_record_id")
private int id;
#Column(name = "std_id")
private String userId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "web_password")
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My DAO class :
public class LoginDAO {
static JKPlainDataAccess dataAccess = JKDataSourceFactory.getPlainDataAccess();
User user;
public boolean validateStudent(String userName, String password) {
user = dataAccess.executeQueryAsSingleObject(User.class, "id,userId,firstName,lastName,password",
"SELECT std_record_id, std_id, first_name, family_name, web_password From students_info WHERE std_id=? and web_password=?",
userName, password);
JK.print("getAllEmployeeRecords() : ", user);
if(user != null) {
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
return true;
}
return false;
}
public static void main(String[] args) {
LoginDAO a = new LoginDAO();
a.validateStudent("200663042001", "1234");
}
}
my xhtml page after the login page:
<ui:composition template="/WEB-INF/layouts/default.xhtml">
<ui:define name="content">
WELCOME Mr. <h:outputLabel value="#{mBLogin.user.firstName}" />
AND <h:outputLabel value="#{mBLogin.user.lastName}" />
</ui:define>
</ui:composition>
When validating, you seem to put the user as the session attribute without assigning it to the Managed Bean field:
session.setAttribute("username", user);
So either assign it also to the instance user variable or simply use:
<ui:composition template="/WEB-INF/layouts/default.xhtml">
<ui:define name="content">
WELCOME Mr. <h:outputLabel value="#{username.firstName}" />
AND <h:outputLabel value="#{username.lastName}" />
</ui:define>
</ui:composition>
Update
I would suggest changing your service method to:
public User validateStudent(..)
where you actually return the queried user instead of setting it in the DAO..
And thus you would change the ManagedBean method to:
public String validteStudent() {
User validatedUser = loginDao.validateStudent(user.getUserId(), user.getPassword());
if (validatedUser != null) {
this.user = validatedUser;
HttpSession session = SessionUtils.getSession();
session.setAttribute("username", user);
....

Passing Parameters from JSF to Applet not working

I am working on a project where I am trying to pass parameters to an applet from JSF. The values (username and roleid) which are being passed as parameters, are fetched from the managed been(loginform). I have an issue with passing these parameters since I get no values in the applet but when I output the values in my web page (for testing purposes), I can clearly see these values. When I hard code the parameter values, I can successfully get the values in the applet, but when I use the values from the manged bean, I get an empty string from the applet. How is this caused and how can I solve it?
View:
<p:idleMonitor onidle="#{loginform.loggout()}" timeout="60000" />
<div id="header">
<div class="pull-left">
Welcome: #{loginform.uname} My Role Id:#{loginform.roleid}
<span style="margin-left:200px;line-height: 10px;">
<h:outputLabel value= "Welcome: #{loginform.uname}" /></span>
</div>
<div class="pull-right">
<h:form>
<h:commandButton class="btn btn-inverse" value="Log Out" action="#
{loginform.loggout()}"/>
</h:form>
</div>
</div>
<APPLET height="900" width="100%" codebase="."
code="finatriall.safe.pro.FinalJApplet.class"
archive="FinalJapplet.jar" >
<param name="username" value="#{loginform.uname}"/>
<param name="role_id" value="loginform.roleid" />
</APPLET>
<!--The section Welcome: #{loginform.uname} My Role Id:#
{loginform.roleid} is used for checking whether values are
successfully returned from the bean-->
Model:
#ManagedBean(name="loginform", eager = true)
#SessionScoped
public class Login {
boolean isLoggedIn;
DBConnection dbcon=new DBConnection();
String username, password;
ArrayList<String> details;
String uname, pwd, message,roleid;
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 getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
public String userLogin(){
String path="";
details=dbcon.loginFunction(username, password);
if(details!=null){
FacesContext.getCurrentInstance().addMessage(null, new
FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", "Login
successful."));
uname=details.get(0);
roleid=details.get(2);
System.out.println("username "+uname);
System.out.println("roleid "+roleid);
path= "/main.xhtml?faces-redirect=true";//Path to launch the
main.xhtml that
contains <>Applet tag>
isLoggedIn=true;
System.out.println("Welcome");
}
else{
System.out.println("Wrong details");
FacesContext.getCurrentInstance().addMessage(null, new
FacesMessage(FacesMessage.SEVERITY_ERROR, "Wrong Credentials",
"User not found."));
path="";
}
return path;
}
public String loggout()
{
FacesContext ctx=FacesContext.getCurrentInstance();
HttpSession sess=
(HttpSession)ctx.getExternalContext().getSession(false);
sess.invalidate();
isLoggedIn=false;
return "/index.xhtml?faces-redirect=true";
}
Applet:
public void init() {
// changeTheme();
jDesktopPane1 = new JDesktopPane();
jDesktopPane1.setBackground(Color.white);
String username=getParameter("separate_jvm");
String roleid = getParameter("role_id");
System.out.println("Role Id: "+roleid);
System.out.println("Username: "+username);
}

Error : javax.el.PropertyNotFoundException: Target Unreachable, 'null' returned null [duplicate]

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?

JSF Datatable does not show all List fields(columns)

I want to display a table in JSF:DataTAble. I successfully retrived table from database to List of users type where "users" is my pojo class. Now I am having problem with displaying it on data table some of the columns like FName, LName, Pwd, displayed correctly but when i add other coulmns like "Note" "Email" it gives me this error
javax.servlet.ServletException: /dt.xhtml: Property 'Email' not found on type in.ali.pojo.users
javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
root cause
javax.el.ELException: /dt.xhtml: Property 'Email' not found on type in.ali.pojo.users
com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385)
com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:162)
javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:894)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
here is my xhtml page
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:dataTable value="#{pretechDataTableBean.user}" var="users">
<h:column>
<f:facet name="header">Name</f:facet>
#{users.FName}
</h:column>
<h:column>
<f:facet name="header">Email</f:facet>
#{users.Email}
</h:column>
<h:column>
<f:facet name="header">Password</f:facet>
#{users.pwd}
</h:column>
</h:dataTable>
</h:body>
</html>
here is my PretechDataTableBean which i used for retrieving data from DB
package com.pretech;
import in.ali.pojo.users;
import in.ali.util.HibernateUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* #author vinod
*/
#ManagedBean
#RequestScoped
public class PretechDataTableBean {
public PretechDataTableBean() {
}
public List<users> getUser() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
List<users> users =null;
try
{
transaction = session.beginTransaction();
users = session.createQuery("from users").list();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
session.close();
}
return users;
}
}
This is my users pojo
package in.ali.pojo;
// Generated Sep 28, 2013 3:55:01 PM by Hibernate Tools 4.0.0
/**
* users generated by hbm2java
*/
public class users implements java.io.Serializable {
private long UserId;
private String FName;
private String LName;
private long UserTypeId;
private String UserName;
private String Email;
private String Pwd;
private String Note;
private boolean IsActive;
public users() {
}
public users(long UserId) {
this.UserId = UserId;
}
public users(long UserId, String FName, String LName, long UserTypeId,
String UserName, String Email, String Pwd, String Note,
boolean IsActive) {
this.UserId = UserId;
this.FName = FName;
this.LName = LName;
this.UserTypeId = UserTypeId;
this.UserName = UserName;
this.Email = Email;
this.Pwd = Pwd;
this.Note = Note;
this.IsActive = IsActive;
}
public long getUserId() {
return this.UserId;
}
public void setUserId(long UserId) {
this.UserId = UserId;
}
public String getFName() {
return this.FName;
}
public void setFName(String FName) {
this.FName = FName;
}
public String getLName() {
return this.LName;
}
public void setLName(String LName) {
this.LName = LName;
}
public long getUserTypeId() {
return this.UserTypeId;
}
public void setUserTypeId(long UserTypeId) {
this.UserTypeId = UserTypeId;
}
public String getUserName() {
return this.UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
public String getEmail() {
return this.Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
public String getPwd() {
return this.Pwd;
}
public void setPwd(String Pwd) {
this.Pwd = Pwd;
}
public String getNote() {
return this.Note;
}
public void setNote(String Note) {
this.Note = Note;
}
public boolean isIsActive() {
return this.IsActive;
}
public void setIsActive(boolean IsActive) {
this.IsActive = IsActive;
}
}
The fields must be likeThis instead of LikeThis. Just change your JSF code to
<h:dataTable value="#{pretechDataTableBean.user}" var="user">
<h:column>
<f:facet name="header">Name</f:facet>
#{user.fName}
</h:column>
<h:column>
<f:facet name="header">Email</f:facet>
#{user.email}
</h:column>
<h:column>
<f:facet name="header">Password</f:facet>
#{user.pwd}
</h:column>
</h:dataTable>
And update the field names in your User class to follow the proper Java Bean naming convention.
public class users implements java.io.Serializable {
private long userId;
private String fName;
private String lName;
private long userTypeId;
private String userName;
private String email;
private String pwd;
private String note;
private boolean isActive;
//constructor, getters and setters
}
Apart from this, there are other bugs in your current design:
You must not have business logic in the getters of your managed bean, instead take advantage of the #PostConstruct method to initialize the necessary data to be used.
Since this bean looks that should stay alive while the user stays in the same view, it will be better to decorate it as #ViewScoped instead of #RequestScoped.
Use proper names for your classes and fields. For example, if you have a List<Something> field, name your variable somethingList or similar in order that the code is self-explanatory.
From these, you can change your managed bean to:
#ManagedBean
#ViewScoped
public class PretechDataTableBean {
private List<users> userList;
public PretechDataTableBean() {
}
#PostConstruct
public void init() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
List<users> users =null;
try
{
transaction = session.beginTransaction();
users = session.createQuery("from users").list();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
session.close();
}
return users;
}
public List<users> getUserList() {
return this.user;
}
}
Since the field changed its name in the managed bean, you should edit it accordingly in the respective view:
<h:dataTable value="#{pretechDataTableBean.userList}" var="user">
Related info:
Why JSF calls getters multiple times
Communication in JSF 2: Managed bean scopes
JavaBeans API Specification , more specifically, Section 7: Properties.

target unreachable 'null' returned null

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 */
}

Resources