PrimeFaces Login [duplicate] - jsf

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.

Related

Display list of images using p:graphicImage in p:dataGrid after uploading image through p:fileUpload

i am uploading multiple images through p:fileUpload and showing uploaded images in datagrid but after upload the blank panel is created inside datagrid
<p:panelGrid columns="1" layout="grid" style="width: 1000px">
<p:outputLabel value="Upload Images"></p:outputLabel>
<p:fileUpload mode="advanced" multiple="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" dragDropSupport="true"
update="messages,updimgsfields,carouselcomp" sizeLimit="100000"
fileUploadListener="#{drawingattachmnt.handleFileUpload}"></p:fileUpload>
<!-- <p:graphicImage id="gimPhoto" value="#{fileuploadSection.image}" /> -->
</p:panelGrid>
<p:fieldset id="updimgsfields" legend="Uploaded Images">
<p:dataGrid id="updimgsdatagrid" var="upldimg"
value="#{drawingattachmnt.uploadedimages}" columns="4">
<p:panel id="drawingattachmntpnl" header="#{upldimg.displayId}"
style="text-align:center">
<h:panelGrid columns="1" cellpadding="5"
style="width: 100%; height: 200px;">
<p:graphicImage value="#{upldimg.imgcontent}" cache="false"
stream="true">
<f:param id="imgId" name="photo_id" value="#{upldimg.id}" />
</p:graphicImage>
</h:panelGrid>
</p:panel>
<p:draggable for="drawingattachmntpnl" revert="true"
handle=".ui-panel-titlebar" stack=".ui-panel" />
</p:dataGrid>
</p:fieldset>
// file upload function inside bean
public void handleFileUpload(final FileUploadEvent event) throws IOException {
if (event.getFile().getContents() != null) {
final ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream();
BufferedImage uploadedImage = null;
byte[] imageBytes = null;
try {
final String imageType = event.getFile().getContentType() != null
|| event.getFile().getContentType().split("/") != null ? event.getFile().getContentType()
.split("/")[1] : "jpeg";
uploadedImage = ImageIO.read(event.getFile().getInputstream());
ImageIO.write(uploadedImage, imageType, byteArrOutputStream);
imageBytes = byteArrOutputStream.toByteArray();
updimg.setImgcontent(new DefaultStreamedContent(new ByteArrayInputStream(imageBytes), imageType));
updimg.setId(UUID.randomUUID().toString().substring(0, 8));
updimg.setDisplayId("FIG: ");
uploadedimages.add(updimg);
} catch (final IOException io) {
} finally {
try {
byteArrOutputStream.close();
// imageInputStream.close();
} catch (final IOException e1) {
e1.printStackTrace();
}
uploadedImage.flush();
}
final FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Successful", "File uploaded Successfully "));
}
// List POJO
import org.primefaces.model.StreamedContent;
public class UploadImage {
public String displayId;
public String id;
public StreamedContent imgcontent;
public UploadImage() {
}
public UploadImage(final String id, final String displayId, final StreamedContent imgcontent) {
this.id = id;
this.displayId = displayId;
this.imgcontent = imgcontent;
}
#Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UploadImage other = (UploadImage) obj;
if (this.id == null ? other.id != null : !this.id.equals(other.id)) {
return false;
}
return true;
}
public String getDisplayId() {
return displayId;
}
public String getId() {
return id;
}
public StreamedContent getImgcontent() {
return imgcontent;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public void setDisplayId(final String displayId) {
this.displayId = displayId;
}
public void setId(final String id) {
this.id = id;
}
public void setImgcontent(final StreamedContent imgcontent) {
this.imgcontent = imgcontent;
}
}
I need to show images in datagrid dynamically, but i am getting blank image panel inside datagrid. what should be done ?

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?

onRowEdit(RowEditEvent event) in prime faces is not getting me updated value [duplicate]

This question already has an answer here:
Edited/updated values in p:dataTable rowEdit are not available in listener method as they are being overwritten by existing data from database
(1 answer)
Closed 7 years ago.
I am trying to update the row using the jsf with primefaces here is my code for each files but when I debug I am not getting updated value it gives me an old value every-time and persist it same as an old one.
user-type.xhtml
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body style="align:center;">
<div style="width: 100%">
<h:form id="form">
<div style="float: left; width: 54%;">
<p:growl id="msgs" showDetail="true" />
<p:dataTable id="userTypesTbl" var="varUserType"
value="#{userTypeTabMenuBean.userTypeMasters}" editable="true"
style="margin-bottom:20px" rowIndexVar="rowIndex">
<f:facet name="header">User Type Managging</f:facet>
<p:ajax event="rowEdit" listener="#{userTypeTabMenuBean.onRowEdit}"
update=":form:msgs" />
<p:ajax event="rowEditCancel"
listener="#{userTypeTabMenuBean.onRowCancel}" update=":form:msgs" />
<p:column headerText="Sr.">
#{rowIndex+1}.
</p:column>
<p:column headerText="Type">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{varUserType.type}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{varUserType.type}" style="width:100%"
label="type" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column>
<f:facet name="header">View</f:facet>
<p:commandButton update=":form" oncomplete="userTypeDialog.show()"
icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{userType}"
var="#{selectedUserType}"
target="#{userTypeTabMenuBean.selectedUserType}" />
</p:commandButton>
</p:column>
<p:column style="width:32px;">
<f:facet name="header">Edit</f:facet>
<p:rowEditor />
</p:column>
<p:column style="width:32px;align-items: center;">
<f:facet name="header">Delete</f:facet>
<h:commandLink
action="#{userTypeTabMenuBean.deleteAction(varUserType)}">
<h:graphicImage library="images" name="delete.png" height="45%"
width="50%" />
</h:commandLink>
</p:column>
</p:dataTable>
<ui:debug hotkey="x" />
<p:dialog header="User type detail" widgetVar="userTypeDialog"
resizable="false" width="330" showEffect="explode"
hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="ID : " />
<h:outputText value="#{userTypeTabMenuBean.selectedUserType.id}" />
<h:outputText value="TYPE: " />
<h:outputText value="#{userTypeTabMenuBean.selectedUserType.type}" />
</h:panelGrid>
</p:dialog>
</div>
<div style="float: right; width: 44%;">
<p:panel menuTitle="Add User Type." header="Add User Type.">
<h:outputText value="User type *:" />
<p:inputText value="#{userTypeTabMenuBean.userType}"
title="Enter User Type.." id="myUserType"
style="margin:0px 10px 0px 10px;"></p:inputText>
<p:commandButton value="Add Type"
action="#{userTypeTabMenuBean.saveAction}" ajax="false">
</p:commandButton>
</p:panel>
</div>
</h:form>
</div>
</h:body>
</html>
UserTypeTabMenuBean.java
package com.convoy.gpack.managedbean;
import java.io.Serializable;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import com.convoy.gpack.dao.UserTypeMasterDAO;
import com.convoy.gpack.pack.models.UserTypeMaster;
#ManagedBean(name = "userTypeTabMenuBean")
#SessionScoped
public class UserTypeTabMenuBean implements Serializable {
private static final long serialVersionUID = 1467465633405172689L;
private static final Logger logger = Logger
.getLogger(UserTypeTabMenuBean.class);
private List<UserTypeMaster> userTypeMasters;
private UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
private UserTypeMaster selectedUserType;
private String userType;
public List<UserTypeMaster> getUserTypeMasters() {
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
logger.info("getUserTypeMasters=" + userTypeMasters);
return userTypeMasters;
}
public String deleteAction(UserTypeMaster userTypeMaster) {
logger.info("Deleting the object with id = " + userTypeMaster.getId());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
int result = userTypeMasterDAO.deleteUserType(userTypeMaster);
userTypeMasters.remove(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage(
"User type deleted successfuly.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to delete user types.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
public void onRowEdit(RowEditEvent event) {
UserTypeMaster userTypeMaster = (UserTypeMaster) event.getObject();
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
userTypeMasterDAO.saveOrUpdateUserTypeMaster(userTypeMaster);
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
FacesMessage msg = new FacesMessage("Edited type ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Editing Cancelled for ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public UserTypeMaster getSelectedUserType() {
return selectedUserType;
}
public void setSelectedUserType(UserTypeMaster selectedUserType) {
this.selectedUserType = selectedUserType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void saveAction() {
logger.info("Saving the object to database...." + userType);
if (userType.trim().length() < 1) {
FacesMessage msg = new FacesMessage("Can not save empty user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
UserTypeMaster userTypeMaster = new UserTypeMaster();
userTypeMaster.setType(userType);
int result = userTypeMasterDAO
.saveOrUpdateUserTypeMaster(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage("User type saved.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to save user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
UserTypeMasterDAO.java
package com.convoy.gpack.dao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.convoy.gpack.hibernate.util.HibernateUtil;
import com.convoy.gpack.pack.models.UserTypeMaster;
public class UserTypeMasterDAO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4005898944892506760L;
public UserTypeMaster getUserTypeById(long long1) {
return null;
}
public List<String> getAllUserTypesInString() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(UserTypeMaster.class);
#SuppressWarnings("unchecked")
List<UserTypeMaster> userTypeMasters = criteria.list();
List<String> userTypeMastersString = new ArrayList<String>();
for (UserTypeMaster userTypeMaster : userTypeMasters) {
userTypeMastersString.add(userTypeMaster.getType());
}
transaction.commit();
session.close();
return userTypeMastersString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<UserTypeMaster> getAllUserTypes() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(UserTypeMaster.class);
#SuppressWarnings("unchecked")
List<UserTypeMaster> userTypeMasters = criteria.list();
transaction.commit();
session.close();
return userTypeMasters;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int saveOrUpdateUserTypeMaster(UserTypeMaster userTypeMaster) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
userTypeMaster.setType(userTypeMaster.getType().toUpperCase());
session.saveOrUpdate(userTypeMaster);
transaction.commit();
session.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public int deleteUserType(UserTypeMaster userTypeMaster) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(userTypeMaster);
transaction.commit();
session.close();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
Thanks in advance ~ :)
Think it might be because of the database values list
#{userTypeTabMenuBean.userTypeMasters}
this always retrieves from the database and that is why getObject() returned an old value ( actually the value from the database)
update the method getUserTypeMasters() as follows
if (userTypeMasters == null){
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
}
return userTypeMasters ;
Exactly Primefaces follows strict structure and I think it is compulsory to add init() method with #PostConstruct annotation.
#PostConstruct
public void init(){
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
}
Here is the solution.
package com.convoy.gpack.managedbean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import com.convoy.gpack.dao.UserTypeMasterDAO;
import com.convoy.gpack.pack.models.UserTypeMaster;
#ManagedBean(name = "userTypeTabMenuBean")
#SessionScoped
public class UserTypeTabMenuBean implements Serializable {
private static final long serialVersionUID = 1467465633405172689L;
private static final Logger logger = Logger
.getLogger(UserTypeTabMenuBean.class);
private List<UserTypeMaster> userTypeMasters;
private UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
private UserTypeMaster selectedUserType;
private String userType;
// This is the required method to get the datatable list.
#PostConstruct
public void init() {
userTypeMasters = userTypeMasterDAO.getAllUserTypes();
logger.info("getUserTypeMasters=" + userTypeMasters);
}
public List<UserTypeMaster> getUserTypeMasters() {
return userTypeMasters;
}
public String deleteAction(UserTypeMaster userTypeMaster) {
logger.info("Deleting the object with id = " + userTypeMaster.getId());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
int result = userTypeMasterDAO.deleteUserType(userTypeMaster);
userTypeMasters.remove(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage(
"User type deleted successfuly.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to delete user types.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return null;
}
public void onRowEdit(RowEditEvent event) {
UserTypeMaster userTypeMaster = (UserTypeMaster) event.getObject();
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
userTypeMasterDAO.saveOrUpdateUserTypeMaster(userTypeMaster);
logger.info("UPDATING THE USER TYPE MASTER : "
+ userTypeMaster.getType());
FacesMessage msg = new FacesMessage("Edited type ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Editing Cancelled for ",
((UserTypeMaster) event.getObject()).getType() + "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public UserTypeMaster getSelectedUserType() {
return selectedUserType;
}
public void setSelectedUserType(UserTypeMaster selectedUserType) {
this.selectedUserType = selectedUserType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void saveAction() {
logger.info("Saving the object to database...." + userType);
if (userType.trim().length() < 1) {
FacesMessage msg = new FacesMessage("Can not save empty user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
UserTypeMasterDAO userTypeMasterDAO = new UserTypeMasterDAO();
UserTypeMaster userTypeMaster = new UserTypeMaster();
userTypeMaster.setType(userType);
int result = userTypeMasterDAO
.saveOrUpdateUserTypeMaster(userTypeMaster);
if (result == 1) {
FacesMessage msg = new FacesMessage("User type saved.");
FacesContext.getCurrentInstance().addMessage(null, msg);
init();
} else if (result == -2) {
FacesMessage msg = new FacesMessage("User type already exist..");
FacesContext.getCurrentInstance().addMessage(null, msg);
} else {
FacesMessage msg = new FacesMessage("Failed to save user type.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
}
That's it~ :)
Thanks #Swathi for the hint.

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

Passing parameters between managedbeans primefaces

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;

Resources