Passing parameters between managedbeans primefaces - jsf

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;

Related

Javascript alert in JSF

I have a method called bilgidorumu() in a managed bean class to check input. If there is a match with database (username and password), the application should go to the welcome page anasayfa.xhtml, else, it stays at the same page (index.xhtml). My problem is that I want to show an alert before staying on the same page (index.xhtml). So if there is no match for username/password, it should display an alert first, and stays then at index.xhtml. But I have no idea how to do that because Javascript runs on client side and Java code in server side. I have tried to display the alert with onclick event but it's not working:
<h:commandButton value="GİRİŞ" styleClass="button" action="#{kntrl.bilgidorumu()}" onclick="onBack()"/>
My input elements to reach via JS function:
<h:inputText id="username" value="#{kntrl.kulad}"
pt:placeholder="username" required="true"
requiredMessage="Kullanıcı adı girilmesi zorunlu"/> <h:inputSecret
id="pw" value="#{kntrl.kulsifre}" pt:placeholder="password"
required="true" requiredMessage="Şifre girilmesi zorunlu"/>
JS function:
function onBack(){
var kulad=document.getElementById("login-form:username").value;
var kulsifre=document.getElementById("login-form:pw").value;
alert(kulad+kulsifre);
}
index.xhtml:
<div class="login-page">
<div class="form">
<h:form class="register-form">
<h:inputText pt:placeholder="name"/>
<input type="password" placeholder="password"/>
<input type="text" placeholder="email address"/>
<button>create</button>
<p class="message">Already registered? Sign In</p>
</h:form>
<h:form class="login-form">
<h:inputText id="username" value="#{kntrl.kulad}" pt:placeholder="username" required="true" requiredMessage="Kullanıcı adı girilmesi zorunlu"/>
<h:message for="username" style="color: red"></h:message>
<h:inputSecret id="pw" value="#{kntrl.kulsifre}" pt:placeholder="password" required="true" requiredMessage="Şifre girilmesi zorunlu"/>
<h:message for="pw" style="color: red; " ></h:message>
<h:commandButton value="GİRİŞ" styleClass="button" action="#{kntrl.bilgidorumu()}" onclick="onBack()"/>
<p class="message">Not registered? Create an account</p>
</h:form>
</div>
</div>
<f:verbatim>
<script type="text/javascript">
function onBack(){
var kulad=document.getElementById("login-form:username").value;
var kulsifre=document.getElementById("login-form:pw").value;
alert(kulad+kulsifre);
}
</script>
</f:verbatim>
Managed bean:
#ManagedBean(name = "kntrl")
#RequestScoped
public class kontrolet {
private int id;
private String adsoyad;
private String birim;
private String bolum;
private String unvan;
private int puan;
private String kulad;
private String kulsifre;
public kontrolet() {
}
public String bilgidorumu() throws ScriptException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/akademiktesvik", "root", "");
String query = "Select * from kisiler";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
if (rs.getString("kulad").equals(kulad) && rs.getString("kulsifre").equals(kulsifre)) {
return "anasayfa?faces-redirect=true";
}
}
} catch (Exception e) {
System.out.println("Baglanti kuurulmadı hata var" + e.getMessage());
}
return "index";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdsoyad() {
return adsoyad;
}
public void setAdsoyad(String adsoyad) {
this.adsoyad = adsoyad;
}
public String getBirim() {
return birim;
}
public void setBirim(String birim) {
this.birim = birim;
}
public String getBolum() {
return bolum;
}
public void setBolum(String bolum) {
this.bolum = bolum;
}
public String getUnvan() {
return unvan;
}
public void setUnvan(String unvan) {
this.unvan = unvan;
}
public int getPuan() {
return puan;
}
public void setPuan(int puan) {
this.puan = puan;
}
public String getKulad() {
return kulad;
}
public void setKulad(String kulad) {
this.kulad = kulad;
}
public String getKulsifre() {
return kulsifre;
}
public void setKulsifre(String kulsifre) {
this.kulsifre = kulsifre;
}
}
I would not recommend to use a JavaScript alert to do so. But, if you really want to, your question would be a duplicate of:
Calling a JavaScript function from managed bean
I would suggest to simply set a message when the username and password do not match and indicate that the validation failed:
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Your message",
"Message details");
context.addMessage(null, message);
context.validationFailed();
Note the null in addMessage, this means we don't set a client ID to the message. This makes the message global. To display it on your page, simply use:
<h:messages globalOnly="true"/>
See also:
How to display my application's errors in JSF?

Fill datatable from database in jpa [duplicate]

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)

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

Catch new value from InputText that have previous Data from DataBase JSF + PrimeFaces 3.5

the problem is to cacth new values after i have previous values from the DB and overwrite them, i wanna save the new values in my beans "variables" and also show the values from de DB in this component, but if i put "Usuario.nombre", it doesnt show the values from the DB, and if i put "datos.nombres" it shows the values from the DB, please help
Here is my xhtml file
<p:dataTable style="width:450px" value="#{DAOUsuario.Listar()}" var="datos">
<p:column headerText="Datos Personales" style="background:#19708F ; color: white">
<p:outputLabel value="Nombre"/>
<h:inputText value="#{datos.nombre}"/>
<br/>
<p:outputLabel value="Clave" />
<h:inputText value="#{datos.clave}"/>
<br/>
<h:commandButton value="Modificar" action="#{DAOUsuario.Modificar()}">
</h:commandButton>
</p:column>
</p:dataTable>
</h:form>
</body>
Here is my Class which have methods to connect to the DB
public void Modificar() throws Exception {
FacesContext context = FacesContext.getCurrentInstance();
Usuario us = (Usuario) context.getApplication().evaluateExpressionGet(context, "#{Usuario}", Usuario.class);
String sql = "UPDATE usuario SET nombre = '" + us.getNombre() + "', clave = '" + us.getClave() + "' "
+ "WHERE codigousuario = 2";
try {
this.Insert(sql);
} catch (Exception ex) {
throw ex;
}
}
and here is my Bean Usuario:
public class Usuario {
private int codigo;
private String nombre;
private String clave;
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
}
Just send the Usuario object as a parameter to your Modificar function:
public void Modificar(Usuario us) throws Exception {
//just to maintain compatibility with your current Usuario us local variable
//FacesContext context = FacesContext.getCurrentInstance();
//Usuario us = (Usuario) context.getApplication().evaluateExpressionGet(context, "#{Usuario}", Usuario.class);
//code goes here...
}
And modify the JSF code to send it in your <p:commandButton>:
<p:dataTable style="width:450px" value="#{DAOUsuario.Listar()}" var="datos">
<p:column headerText="Datos Personales" style="background:#19708F ; color: white">
<p:outputLabel value="Nombre"/>
<h:inputText value="#{datos.nombre}"/>
<br/>
<p:outputLabel value="Clave" />
<h:inputText value="#{datos.clave}"/>
<br/>
<h:commandButton value="Modificar" action="#{DAOUsuario.Modificar(datos)}" />
</p:column>
</p:dataTable>
Outside of the question scope, as a recommendation, don't use your DAO classes as managed beans, it would be better to leverage the coupling in your application by having at least these logical layers:
Controller layer (for the JSF/CDI managed beans)
Business/Service layer (business logic goes here)
Data access layer (here are the DAO classes)
Another recommendation: please follow the JavaBeans naming conventions for class and function naming, you can have a quick review here. As an example, your DAOUsuario functions should be listar instead of Listar and modificar instead of Modificar.

PrimeFaces Login [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSF HTTP Session Login
Avoid back button on JSF+Primefaces application
Primefaces Login Application
I have developed web application by using Prime Faces.Now I want to improve the login system in here up to now I have done followings..
1. index.xhtml
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" value="Username:" />
<p:inputText value="#{loginBean.username}"
id="username" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<h:inputSecret value="#{loginBean.password}"
id="password" required="true" label="password" />
<f:facet name="footer">
<p:commandButton id="loginButton" value="Login" update=":growl" action="#{loginBean.doLogin}" actionListener="#{loginBean.login}" oncomplete="handleLoginRequest(xhr, status, args)" style="height: 30px; font-size: 12px" />
<p:commandButton type="reset" value="Clear" style="height: 30px; font-size: 12px"/>
</f:facet>
</h:panelGrid>
</h:form>
2.LoginBean.java
public class LoginBean {
private String username;
private String password;
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 List<user> getUser() {
List<user> tableList = new ArrayList<user>();
String query = "SELECT * FROM users";
try {
Connection conn = new Connector().getConn();
Statement select = conn.createStatement();
ResultSet result = select.executeQuery(query);
while (result.next()) {
user c = new user();
c.setID(result.getInt("ID"));
c.setName(result.getString("name"));
c.setPassword(result.getString("password"));
tableList.add(c);
}
select.close();
// result.close();
conn.close();
} catch (SQLException e) {
System.err.println("Mysql Statement Error: " + query);
e.printStackTrace();
}
//System.out.println(tableList);
return tableList;
}
public void login(ActionEvent actionEvent) {
List<user> tableList3=getUser();
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg = null;
boolean loggedIn = false;
for(int i=0;i<tableList3.size();i++){
String user_name = tableList3.get(i).getName();
String pass_word = tableList3.get(i).getPassword();
if(username != null && username.equals(user_name) && password != null && password.equals(pass_word)) {
loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
//return "table?faces-redirect=true";
} else {
loggedIn = false;
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
//return "new?faces-redirect=true";
}
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
}
}
public String doLogin(){
List<user> tableList2=getUser();
String msg = null;
for(int i=0;i<tableList2.size();i++){
String user_name = tableList2.get(i).getName();
String pass_word = tableList2.get(i).getPassword();
if(username != null && username.equals("admin") && password != null && password.equals("admin")){
msg = "table?faces-redirect=true";
}
else if(user_name.contains(username)&& pass_word.contains(password)&& !user_name.contains("admin")) {
msg = "table1?faces-redirect=true";
}
}
return msg;
}
public String logout() {
return "index?faces-redirect=true";
}
}
In here the users can load the pages with out logged in to the system.I want to prevent this by using session.But I have not clear idea how to do this.So please help me to do this by step by step.
Thank you.

Resources