I am starting out using JSF and I am trying to add a record to a database using the details entered into the form by the user. My XHTML page includes this form.
<h:form>
<table id ="addRecordTable">
<tr>
<td><h:outputText value="Enter Name: " /></td>
<td><h:inputText value="#{animal.name}" id="name" label="name" required="true" requiredMessage="Name is required.">
<f:validateLength minimum="2" maximum="15"></f:validateLength>
</h:inputText>
</td>
</tr>
<tr>
<td><h:outputText value="Enter Age: "/></td>
<td><h:inputText value="#{animal.age}" id="age" label="age" required="true" requiredMessage="Age is required."></h:inputText></td>
</tr>
<tr>
<td><h:outputText value="Enter Breed : " /></td>
<td><h:inputText value="#{animal.breed}" id="breed" label="breed" required="true" requiredMessage="Breed is required.">
<f:validateLength minimum="2" maximum="15"></f:validateLength>
</h:inputText>
</td>
</tr>
<tr>
<td></td>
<td><h:commandButton value="Add" action="#{animalBean.add}">
<f:setPropertyActionListener target="#{animalBean.animal.age}" value="#{animal.age}" />
<f:setPropertyActionListener target="#{animalBean.animal.name}" value="#{animal.name}" />
<f:setPropertyActionListener target="#{animalBean.animal.breed}" value="#{animal.breed}" />
</h:commandButton></td>
</tr>
</table>
</h:form>
I also have these java Managed Bean classes:
import javax.faces.bean.ManagedBean;
#ManagedBean
public class Animal {
private int id;
private String breed;
private int age;
private String name;
public Animal(int id, int age, String breed, String name) {
this.breed = breed;
this.age = age;
this.id = id;
this.name = name;
}
public Animal()
{
this.breed= "";
this.age = 0;
this.id = 0;
this.name= "";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getBreed() {
return breed;
}
public int getAge() {
return age;
}
#Override
public String toString()
{
return "Animal [id=" + id + ", breed=" + breed + ", age=" + age
+ ", name=" + name + "]";
}
}
and....
import javax.faces.bean.ManagedBean;
#ManagedBean
public class AnimalBean
{
protected Animal animal = new Animal();
public List <Animal> getAnimals() {
List <Animal> animals = new ArrayList <Animal> ();
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\lwilson\\Animals.accdb";
try {
con = DriverManager.getConnection(url);
System.out.println("Connection completed (Select All).");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
String stm = "SELECT Breed,Age,Name, ID FROM Animals";
try {
pst = con.prepareStatement(stm);
pst.executeQuery();
rs = pst.getResultSet();
while (rs.next()) {
int age = rs.getInt("Age");
String breed = rs.getString("Breed");
String name= rs.getString("Name");
int id = rs.getInt("ID");
Animal a1 = new Animal(id,age, breed, name);
animals.add(a1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return animals;
}
public void add() {
File db = new File("C:\\Users\\lwilson\\Animals.accdb");
if (!db.exists()) {
System.out.println("file not found");
}
PreparedStatement ps = null;
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\lwilson\\Animals.accdb";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url, "", "");
String sql = "INSERT INTO Animals(Age, Breed, Name) VALUES(?,?,?)";
ps = con.prepareStatement(sql);
ps.setInt(1, animal.getAge());
ps.setString(2, animal.getBreed());
ps.setString(3, animal.getName());
ps.executeUpdate();
System.out.println("Data Added Successfully Into Database");
} catch (Exception e) {
System.out.println(e);
System.out.println("exception here");
}
}
My issue is that in the setPropertyActionListener, the target does not set the Animal object field to the value from the form. I receive an error saying that the target cannot access the field of the created animal object. These fields are then in turn passed into the add() method.
Any help would be appreciated. Thanks.
You can inject your Animal class object into your AnimalBean class using #ManagedProperty annotation as
#ManagedBean
public class AnimalBean {
#ManagedProperty
protected Animal animal;
// getter and setter
// Here your other methods
}
In this case no need to use
<f:setPropertyActionListener target="#{animalBean.animal.age}" value="#{animal.age}" />
<f:setPropertyActionListener target="#{animalBean.animal.name}" value="#{animal.name}" />
<f:setPropertyActionListener target="#{animalBean.animal.breed}" value="#{animal.breed}" />
You will get your property value using Animal class getter and setter.
It should looks like this:
1) Getter and setter for animal object in managed bean class
2) Refering in form to animal object by #{animalBean.animal.value}
3) When you post your form then animal object will be updated automatic. Property action listeners are unnecessary.
Related
my pb is that when I select an item to display items in the second selectOneMenu () the submit button does not work.
at the second click the button tries to submit the form but (this action emptie the second SOM) as the second SelectOneMenu becomes empty its trigger a validation error.
primefaces 6.1
jsf2.2
tomcat8.5
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<h:panelGroup id="addProjet2" rendered="true">
<table>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2">
</h:outputLabel></td>
<td><p:selectOneMenu id="Client2"
value="#{creerintervention.selected_client}" effect="fade"
style="width:100px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_client}" var="cl"
itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="create_intervention_form:station1_client"
listener="#{creerintervention.getStructureByClient}"
process="Client2" />
</p:selectOneMenu> <p:selectOneMenu id="station1_client"
value="#{creerintervention.selectedStation}" style="width:100px"
filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_Station}"
var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
<p:ajax partialSubmit="false" />
</p:selectOneMenu></td>
</tr>
<tr>
<p:commandButton value="Valider" pdate="create_intervention_form"
id="valide" actionListener="#{creerintervention.addOdm}"
styleClass="ui-priority-primary" />
</tr>
</table>
</h:panelGroup>
</h:form>
ManagedBean
#RequestScoped
#Management(name = "creerintervention")
public class CreerIntervention {
private String matricule;
private agentService agentservice = new agentServiceImpl();
private usersService usersService = new usersServiceImpl();
private clientService clientService = new clientServiceImpl();
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> StationList;
private List<SelectItem> StationList;
private station selectedStation;
private client Selected_client;
{
//*** initialiser la liste des client dans le SelectOnMenu
list_client = clientService.findAll();
}
public void getStructureByClient()
{
// ######## Préparer la liste des nom des clients ######## //
list_Station=stationService.findByRefClient(getSelected_client().getRef());
log.info("La refernce du client est ---"+ Selected_client.getRef());
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.size());
}
public void addOdm(ActionEvent e)
{
log.info("Matricule:" + matricule) ;
log.info("destination:" +destination);
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ selectedStation.getNom_stat());
log.info("objet mission:"+ obj_mission );
log.info("date depart:"+ date_dep );
log.info("date ret:"+ date_retour );
log.info("moyen transp:"+ moyen_transport) ;
log.info("imma:"+ immatriculation) ;
log.info("prise en charge :"+ prise_en_charge) ;
log.info("struct:"+ structure) ;
}
.....
Setters and Getters...
I have get the solution ; the problem was in the Scope the right one is #ViewScoped.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<table>
<tr>
<td><p:outputLabel value="Matricule:" for="Matricule" /></td>
<td><p:inputText id="Matricule"
value="#{teststation.matricule}" size="5" /></td>
</tr>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2"></h:outputLabel> </td>
<td>
<p:panel id="st">
<p:selectOneMenu id="Client2" value="#{teststation.selected_client}">
<f:selectItems value="#{teststation.list_client}" var="cl" itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="station1_client" listener ="#{teststation.getStructureByClient}" />
</p:selectOneMenu>
<p:selectOneMenu id="station1_client" value="#{teststation.selectedStation}" >
<f:attribute name="selected_station" value="#{teststation.selectedStation}" />
<f:selectItems value="#{teststation.list_Station}" var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
</p:selectOneMenu>
</p:panel>
</td>
</tr>
<tr>
<td><h:outputLabel value="Immatriculation:" for="imma"></h:outputLabel> </td>
<td><p:inputText size="20" value="#{teststation.immatriculation}" id="imma"></p:inputText></td>
</tr>
<tr>
<p:growl id="growl" life="2000" />
<td></td>
<td><p:commandButton value="Valider" id="valide" update="errorMessages" actionListener="#{teststation.addOdm}" styleClass="ui-priority-primary" />
</td>
</tr>
</table>
</h:form>
</h:body>
</html>
the ManagedBean
#ViewScoped
#ManagedBean(name = "teststation")
public class TestStation {
private String matricule;
private stationService stationService = new stationServiceImpl();
private clientService clientService = new clientServiceImpl();
public static Logger log = LogManager.getLogger(CreerIntervention.class.getName());
private String nom;
private String client_name;
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> stationList;
private List<SelectItem> stationList;
private String immatriculation;
private String ref_Selected_client;
private String Nom_Selected_client;
private String ref_Selected_station;
private String Nom_Selected_station;
private List<station> station;
private station selectedStation;
private client Selected_client;
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
Map<String, String> selectedStationParam= fc.getExternalContext().getRequestParameterMap();
#PostConstruct
public void initMyBean()
{
log.info("ici PosteConstract"+this.getClass().hashCode());
}
public TestStation()
{
super();
log.info("ici Constract "+this.getClass().hashCode());
}
{
list_client = clientService.findAll();
}
public void updateSelectedStation()
{
log.info("LES updateSelectedStatio ---"+ list_Station.get(0).getNom_stat());
}
public void getStructureByClient()
{
log.info("La refernce du client selectioné est --- "+ Selected_client.getRef());
list_Station=stationService.findByRefClient(getSelected_client().getRef());
stationList= new ArrayList<>();
for (station o : list_Station)
{
stationList.add(new SelectItem(o.getNom_stat(),o.getRef_stat()));
}
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.get(0).getNom_stat());
}
public void addOdm()
{ Nom_Selected_station=selectedStation.getNom_stat();
//log.info("num_odm :" + num_odm) ;
log.info("Matricule:" + matricule) ;
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ Nom_Selected_station);
log.info("imma:"+ immatriculation) ;
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void cancelAction(ActionEvent e)
{
log.info("etat valeur ShowForm555 = ");
}
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getNom_Selected_client() {
return Nom_Selected_client;
}
public void setNom_Selected_client(String nom_Selected_client) {
Nom_Selected_client = nom_Selected_client;
}
public String getRef_Selected_client() {
return ref_Selected_client;
}
public void setRef_Selected_client(String Ref_Selected_client) {
this.ref_Selected_client = Ref_Selected_client;
}
public String getClient_name() {
return client_name;
}
public void setClient_name(String client_name) {
this.client_name = client_name;
}
/*public Map<String, String> getClientList() {
return clientList;
}
public void setClientList(Map<String, String> clientList) {
this.clientList = clientList;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}*/
public String getImmatriculation() {
return immatriculation;
}
public void setImmatriculation(String immatriculation) {
this.immatriculation = immatriculation;
}
public List<station> getStation() {
return station;
}
public void setStation(List<station> station) {
this.station = station;
}
/*public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}*/
/*public Map<String, String> getStationList() {
return stationList;
}
public void setStationList(Map<String, String> stationList) {
stationList = stationList;
}*/
public void setClientList(List<SelectItem> clientList) {
this.clientList = clientList;
}
public List<SelectItem> getStationList() {
return stationList;
}
public void setStationList(List<SelectItem> stationList) {
this.stationList = stationList;
}
public List<SelectItem> getClientList() {
return clientList;
}
public station getSelectedStation() {
return selectedStation;
}
public void setSelectedStation(station selectedStation) {
this.selectedStation = selectedStation;
}
public client getSelected_client() {
return Selected_client;
}
public void setSelected_client(client selected_client) {
Selected_client = selected_client;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}
public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}
public String getRef_Selected_station() {
return ref_Selected_station;
}
public void setRef_Selected_station(String ref_Selected_station) {
this.ref_Selected_station = ref_Selected_station;
}
public String getNom_Selected_station() {
return Nom_Selected_station;
}
public void setNom_Selected_station(String nom_Selected_station) {
Nom_Selected_station = nom_Selected_station;
}
}
the StationConverter
#FacesConverter("StationConverter")
public class StationConverter implements Converter {
public static Logger log = LogManager.getLogger(StationConverter.class.getName());
stationService statServ = new stationServiceImpl();
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
log.info("4- submitted value for Station Converter ********** "+submittedValue);
log.info("5- returned Object for Station Converter ********** "+statServ.findByRef(submittedValue).getNom_stat());
return statServ.findByRef(submittedValue);
} catch (NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Client ID"));
}}
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
log.info(modelValue.getClass());
if (modelValue instanceof station ) {
log.info( "6- la valeur en String Converter Station est ****** "+String.valueOf(((station) modelValue).getNom_stat()));
return String.valueOf(((station) modelValue).getRef_stat());
} else {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Station instance"));
}
}
}
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?
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.
I want to delete selected row from data table when click on GraphicImage under CommandLink.
but it is don't work for me.
it gives error :-
/privilegepage.xhtml #66,21 action="#{privilegeManagedBean.deleteAction(p)}" Failed to parse the expression [#{privilegeManagedBean.deleteAction(p)}]
Bean:-Privilege
public class Privilege {
private int id;
private String privilege;
public Privilege() {
}
public Privilege(int id, String privilege) {
this.id = id;
this.privilege = privilege;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
}
bean:- PrivilegeDao.java
public int deletePrivilege(int id) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "delete privilege from privilege where id=?";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setInt(2, id);
if(preparedStatement.executeUpdate()==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is delete :- ");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}
bean :-PrivilegeManagedBean
#ManagedBean(name = "privilegeManagedBean", eager = true)
#SessionScoped
/* #ManagedProperty(value="#param.id") */
public class PrivilegeManagedBean {
private int id;
private String privilege;
private PrivilegeDao pdao;
#SuppressWarnings("unused")
private List<Privilege> privilegeData;
private static int srno;
private int selectedRowIndex = -1;
public PrivilegeManagedBean() {
privilegeData = new ArrayList<Privilege>();
pdao = new PrivilegeDao();
srno = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
public void setPrivilegeData(List<Privilege> privilegeData) {
this.privilegeData = privilegeData;
}
public List<Privilege> getPrivilegeData() {
return this.privilegeData = pdao.getUserList();
}
public int getSelectedRowIndex() {
return selectedRowIndex;
}
public void setSelectedRowIndex(int selectedRowIndex) {
this.selectedRowIndex = selectedRowIndex;
}
public void addDataTableRow() {
pdao.addRow(this.id, this.privilege);
}
private static ArrayList<Privilege> privilegeList = new ArrayList<Privilege>();
public ArrayList<Privilege> getPrivilegeList() {
return privilegeList;
}
public void setPrivilegeList(ArrayList<Privilege> privilege) {
privilegeList = (ArrayList<Privilege>) pdao.getUserList();
}
public int addAction() {
Privilege privilegeitem = new Privilege(this.id, this.privilege);
privilegeList.add(privilegeitem);
return pdao.addPrivilege(this.privilege);
}
public int deleteAction() {
Privilege privilegeitem = new Privilege(this.id, this.privilege);
privilegeList.remove(privilegeitem);
System.out.println("delete Action...");
return pdao.deletePrivilege(this.id);
}
public int onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Privilege Edited",
((Privilege) event.getObject()).getPrivilege());
FacesContext.getCurrentInstance().addMessage(null, msg);
int pid = pdao.getPrivilegeId(this.privilege);
System.out.println("Privilege Name For Id :- " + this.privilege);
System.out.println("Privilege Id :- " + pid);
return pdao.updatePrivilege(pid, this.privilege);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage("Privilege Cancelled");
FacesContext.getCurrentInstance().addMessage(null, msg);
privilegeList.remove((Privilege) event.getObject());
}
public String deletePrivilege(Privilege privilege) {
privilegeList.remove(privilege);
return null;
}
public int getSrno() {
return ++srno;
}
}
Privilege.xhtml
<p:growl id="messages" showDetail="true" />
<p:dataTable value="#{privilegeDao.userList}" var="p"
id="datatbldispprivilege" style="width:500px" editable="true" lazy="true">
<f:facet name="header">
Privilege List
</f:facet>
<p:ajax event="rowEdit" listener="#{privilegeManagedBean.onEdit}"
update=":form1:messages" />
<p:ajax event="rowEditCancel"
listener="#{privilegeManagedBean.onCancel}" update=":form1:messages" />
<p:column headerText="Privileges Name">
<p:cellEditor>
<f:facet name="output">
<p:outputLabel value="#{p.privilege}" name="privilegeoutputname" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{privilegeManagedBean.privilege}"
name="privilegeinputname" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Options" style="width:100px">
<p:rowEditor>
</p:rowEditor>
</p:column>
<p:column headerText="Delete" style="width:100px">
<p:commandLink action="#{privilegeManagedBean.deleteAction(p)}"
update="#form">
<p:graphicImage value="/images/deleteicon.png" library="images"
onclick="if (!confirm('Are you sure you want to delete the current record?')) return false"
width="20px" height="20px" />
<f:param name="pname" value="#{p.name}" />
</p:commandLink>
</p:column>
</p:dataTable>
Your PrivilegeManagedBean#deleteAction don't accepts any arguments, but your JSF code passes the current iteration of the data table value to the method. So either don't pass anything to the method:
<p:commandLink action="#{privilegeManagedBean.deleteAction()}" update="#form">
or change the method signature of PrivilegeManagedBean#deleteAction.
you're trying to call the wrong method. action should be like this:
<p:commandLink action="#{privilegeManagedBean.deletePrivilege(p)}" update="#form">
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;