This question already has answers here:
commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated
(12 answers)
Closed 6 years ago.
I'm new to JSF.I followed a tutorial of JSF step by step but I'm unable to get the data from ManagedBean to xhtml page when I run it.Below are each class I have created.
UserData.java
package com.practise.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "userData", eager = true)
#SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String dept;
private int age;
private double salary;
private static final ArrayList<Employee> employees
= new ArrayList<Employee>(Arrays.asList(
new Employee("John", "Marketing", 30,2000.00),
new Employee("Robert", "Marketing", 35,3000.00),
new Employee("Mark", "Sales", 25,2500.00),
new Employee("Chris", "Marketing", 33,2500.00),
new Employee("Peter", "Customer Care", 20,1500.00)
));
public ArrayList<Employee> getEmployees() {
return employees;
}
public String addEmployee() {
Employee employee = new Employee(name,dept,age,salary);
employees.add(employee);
return null;
}
public String deleteEmployee(Employee employee) {
employees.remove(employee);
return null;
}
public String editEmployee(Employee employee){
employee.setCanEdit(true);
return null;
}
public String saveEmployees(){
//set "canEdit" of all employees to false
for (Employee employee : employees){
employee.setCanEdit(false);
}
return null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return dept;
}
public void setDepartment(String department) {
this.dept = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Employee.java
package com.practise.test;
public class Employee {
private String name;
private String department;
private int age;
private double salary;
private boolean canEdit;
public Employee (String name,String department,int age,double salary){
this.name = name;
this.department = department;
this.age = age;
this.salary = salary;
canEdit = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public boolean isCanEdit() {
return canEdit;
}
public void setCanEdit(boolean canEdit) {
this.canEdit = canEdit;
}
}
home.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>JSF tutorial</title>
<h:outputStylesheet library="css" name="styles.css" />
</h:head>
<h:body>
<h2>DataTable Example</h2>
<h:form>
<h:dataTable value="#{userData.employees}" var="employee"
styleClass="employeeTable"
headerClass="employeeTableHeader"
rowClasses="employeeTableOddRow,employeeTableEvenRow">
<h:column>
<f:facet name="header">Name</f:facet>
#{employee.name}
</h:column>
<h:column>
<f:facet name="header">Department</f:facet>
#{employee.department}
</h:column>
<h:column>
<f:facet name="header">Age</f:facet>
#{employee.age}
</h:column>
<h:column>
<f:facet name="header">Salary</f:facet>
#{employee.salary}
</h:column>
</h:dataTable>
<h3>Add Employee</h3>
<hr/>
<table>
<tr>
<td>Name :</td>
<td><h:inputText size="10" value="#{userData.name}" /></td>
</tr>
<tr>
<td>Department :</td>
<td><h:inputText size="20" value="#{userData.dept}" /></td>
</tr>
<tr>
<td>Age :</td>
<td><h:inputText size="5" value="#{userData.age}" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><h:inputText size="5" value="#{userData.salary}" /></td>
</tr>
<tr>
<td> </td>
<td><h:commandButton value="Add Employee"
action="#{userData.addEmployee}" /></td>
</tr>
</table>
</h:form>
</h:body>
</html>
Can someone help me out to figure out what is the exact issue and how to overcome it.Thanks in advance.
Because you have userData.dept, expression language will look for getDept()/setDept() methods which u don't have. which will throw an error. You need use the proper naming.
Change
<h:inputText size="20" value="#{userData.dept}" />
To
<h:inputText size="20" value="#{userData.department}" />
Related
I'm sure this is a common problem but I can't seem to find a solution to it at all. Basically when I add the data I want into each of the input text boxes and click the command button all seen on the input page below, The data does not go through to the designated data table and I am left with null values instead.
This is the xhtml code for inputting those values:
<h3> Please fill in the boxes below and click save when you have finished.</h3>
<h:form>
<table>
<tr>
<td>Id Number :</td>
<td><h:inputText size="20" value="#{collectors.ID}" /></td>
</tr>
<tr>
<td>Name :</td>
<td><h:inputText size="20" value="#{collectors.name}" /></td>
</tr>
<tr>
<td>Release Date :</td>
<td><h:inputText size="20" value="#{collectors.releaseDate}" /></td>
</tr>
<tr>
<td>Platform :</td>
<td><h:inputText size="20" value="#{collectors.platform}" /></td>
</tr>
<tr>
<td>Genre :</td>
<td><h:inputText size="20" value="#{collectors.genre}" /></td>
</tr>
<tr>
<td>Developer :</td>
<td><h:inputText size="20" value="#{collectors.developer}" /></td>
</tr>
<tr>
<td>Publisher :</td>
<td><h:inputText size="20" value="#{collectors.publisher}" /></td>
</tr>
</table>
<h:commandButton value="SAVE" action="#{collectors.saveAction}" />
</h:form>
This is the code for data table that should display that data:
<h:form>
<h:dataTable value="#{collectors.collectionList}" var="c" border ="2">
<h:column>
<f:facet name="header">
ID NO
</f:facet>
#{c.ID}
</h:column>
<h:column>
<f:facet name="header">
Name
</f:facet>
#{c.name}
</h:column>
<h:column>
<f:facet name="header">
Release Date
</f:facet>
#{c.releaseDate}
</h:column>
<h:column>
<f:facet name="header">
Platform
</f:facet>
#{c.platform}
</h:column>
<h:column>
<f:facet name="header">
Genre
</f:facet>
#{c.genre}
</h:column>
<h:column>
<f:facet name="header">
Developer
</f:facet>
#{c.developer}
</h:column>
<h:column>
<f:facet name="header">
Publisher
</f:facet>
#{c.publisher}
</h:column>
<h:column>
<f:facet name="header">Action</f:facet>
<h:commandLink value="Delete" action="#{collectors.deleteAction(c)}" />
</h:column>
</h:dataTable>
And my Java Managed Bean Code:
package bean;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
#Named(value = "collectors")
#SessionScoped
public class CollectorsBean implements Serializable{
private static final long serialVersionUID = 1L;
int ID;
String Name;
String ReleaseDate;
String Platform;
String Genre;
String Developer;
String Publisher;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getReleaseDate() {
return ReleaseDate;
}
public void setReleaseDate(String ReleaseDate) {
this.ReleaseDate = ReleaseDate;
}
public String getPlatform() {
return Platform;
}
public void setPlatform(String Platform) {
this.Platform = Platform;
}
public String getGenre() {
return Genre;
}
public void setGenre(String Genre) {
this.Genre = Genre;
}
public String getDeveloper() {
return Developer;
}
public void setDeveloper(String Developer) {
this.Developer = Developer;
}
public String getPublisher() {
return Publisher;
}
public void setPublisher(String Publisher) {
this.Publisher = Publisher;
}
private static final ArrayList<Entry> collectionList=
new ArrayList<Entry>(Arrays.asList(
new Entry (1, "Persona 5", " 4th April 2017", "Playstation 4", "Social Simulator/RolePlaying","Atlus","Deep Silver" )
));
public ArrayList <Entry> getCollectionList(){
return collectionList;
}
public String saveAction(){
Entry entry = new Entry(this.ID, this.Name, this.ReleaseDate, this.Platform, this.Genre, this.Developer, this.Publisher);
collectionList.add(entry);
return "Collection Page.xhtml";
}
public String deleteAction(Entry entry) {
collectionList.remove(entry);
return null;
}
public static class Entry{
int ID;
String Name;
String ReleaseDate;
String Platform;
String Genre;
String Developer;
String Publisher;
public Entry(int ID, String Name, String ReleaseDate, String Platform, String Genre, String Developer, String Publisher)
{
this.ID = ID;
this.Name = Name;
this.ReleaseDate = ReleaseDate;
this.Platform = Platform;
this.Genre = Genre;
this.Developer = Developer;
this.Publisher = Publisher;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getReleaseDate() {
return ReleaseDate;
}
public void setReleaseDate(String ReleaseDate) {
this.ReleaseDate = ReleaseDate;
}
public String getPlatform() {
return Platform;
}
public void setPlatform(String Platform) {
this.Platform = Platform;
}
public String getGenre() {
return Genre;
}
public void setGenre(String Genre) {
this.Genre = Genre;
}
public String getDeveloper() {
return Developer;
}
public void setDeveloper(String Developer) {
this.Developer = Developer;
}
public String getPublisher() {
return Publisher;
}
public void setPublisher(String Publisher) {
this.Publisher = Publisher;
}
}
}
I'd be very grateful if someone could help me solve this.
While selecting a dropdown,the second drop down values are not coming properly.I am attaching the code here
xhtml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<f:event listener="#{userData.handleEvent}" type="preRenderView" />
</h:head>
<h:body>
<f:view>
<h:form >
<table>
<tr>
<td> <h:messages showDetail="true" /> </td>
</tr>
<tr>
<td><h:outputText value="Enter name : "/></td>
<td><h:inputText value="#{userData.clientname}"/></td>
</tr>
<tr>
<td><h:outputText value="Enter Id : " /></td>
<td><h:inputText value="#{userData.id}" /></td>
</tr>
<tr>
<td></td>
<td><h:commandButton value="Insert" action="#{userData.add}"/></td>
</tr>
<tr>
<td></td>
<td>#{userData.data}</td>
</tr>
<tr>
<td><h:selectOneRadio value="#{authorData.favColor1}" id="div2">
<f:selectItem itemValue="Red" itemLabel="Color1 - Red" />
<f:selectItem itemValue="Green" itemLabel="Color1 - Green"/>
<f:ajax event="click" binding="valbinding" execute="#form" render=":div1" listener="#{authorData.setchangeval}"/>
</h:selectOneRadio></td>
</tr>
</table>
</h:form>
<h:panelGroup id="div1" style="display: #{authorData.valdisplay};">
<span>
You have selected #{authorData.message}
</span>
</h:panelGroup>
</f:view>
<br/>
<h:outputLabel value="Choose your Car: * " for="firstdropdwn" />
<h:selectOneMenu id="firstdropdwn" value="#{authorData.favoriteCar2}">
<f:selectItems value="#{authorData.car4List}" var="d"
itemLabel="#{d.carlabel}" itemValue="#{d.carvalue}"/>
<f:ajax event="click" binding="valbinding1" execute="#this firstdropdwn" render=":seconddrpdown" listener="#{authorData.setDropDwnVal}"/>
</h:selectOneMenu>
<br/>
<h:outputLabel value="Choose your Owner: * " for="seconddrpdown" />
<h:selectOneMenu id="seconddrpdown" value="">
<f:selectItems value="#{authorData.car3List}" var="c"
itemLabel="#{c.carlabel}" itemValue="#{c.carvalue}"/>
</h:selectOneMenu>
</h:body>
</html>
Author.java:
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.ComponentSystemEvent;
#ManagedBean(name = "authorData", eager = true)
#SessionScoped
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
String clientname;
String id;
String favColor1;
public String favoriteCar2;
private UIComponent valbinding;
private UIComponent valbinding1;
public List<Car> car3List;
/*public Car[] getFavoriteCar3Value()
{
car3List = new Car[3];
car3List[0] = new Car("BMW Series 4 - 316", "316");
car3List[1] = new Car("BMW Series 4 - 318", "318");
car3List[2] = new Car("BMW Series 4 - 320", "320");
return car3List;
}
*/
public List<Car> getCar3List() {
return car3List;
}
public void setCar3List(List<Car> car) {
this.car3List = car;
}
public List<Car> car4List;
public List<Car> getCar4List() {
car4List = new ArrayList<Car>();
car4List.add(new Car("BMW","116"));
car4List.add(new Car("AUDI","118"));
car4List.add(new Car("MERCEDES","120"));
return car4List;
}
public UIComponent getValbinding1() {
return valbinding1;
}
public void setValbinding1(UIComponent valbinding1) {
this.valbinding1 = valbinding1;
}
private String valdisplay="none";
private String message;
public String getFavoriteCar2() {
return favoriteCar2;
}
public void setFavoriteCar2(String favoriteCar2) {
this.favoriteCar2 = favoriteCar2;
}
private static Map<String, String> favoriteCar2Value;
static
{
favoriteCar2Value = new LinkedHashMap<String, String>();
favoriteCar2Value.put("BMW Series 1 - 116", "116"); //label, value
favoriteCar2Value.put("BMW Series 1 - 118", "118");
favoriteCar2Value.put("BMW Series 1 - 120", "120");
}
public Map<String, String> getFavoriteCar2Value()
{
return favoriteCar2Value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getValdisplay() {
return valdisplay;
}
public void setValdisplay(String valdisplay) {
this.valdisplay = valdisplay;
}
public UIComponent getValbinding() {
return valbinding;
}
public void setValbinding(UIComponent valbinding) {
this.valbinding = valbinding;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClientname() {
return clientname;
}
public void setClientname(String clientname) {
this.clientname = clientname;
}
public String getFavColor1() {
return favColor1;
}
public void setFavColor1(String favColor1) {
this.favColor1 = favColor1;
}
public void setchangeval(AjaxBehaviorEvent e){
this.setValdisplay("none");
if(this.getFavColor1().equalsIgnoreCase("red")){
this.setValdisplay("block");
this.setMessage("RED");
}else if(this.getFavColor1().equalsIgnoreCase("Green")){
this.setValdisplay("block");
this.setMessage("GREEN");
}
}
public void setDropDwnVal(AjaxBehaviorEvent e){
if(this.getFavoriteCar2().equalsIgnoreCase("116")){
LinkedList<Car> ob = new LinkedList<Car>();
ob.add(new Car("Aife","0"));
ob.add(new Car("Anirban","1"));
this.setCar3List(ob);
}else {
LinkedList<Car> ob1 = new LinkedList<Car>();
ob1.add(new Car("Saife","0"));
ob1.add(new Car("Abid","1"));
this.setCar3List(ob1);
}
}
}
Car.java:
import java.io.Serializable;
public class Car implements Serializable {
public String carlabel;
public String carvalue;
public Car(String carLabel, String carValue) {
this.carlabel=carLabel;
this.carvalue=carValue;
}
public String getCarlabel() {
return carlabel;
}
public void setCarlabel(String carlabel) {
this.carlabel = carlabel;
}
public String getCarvalue() {
return carvalue;
}
public void setCarvalue(String carvalue) {
this.carvalue = carvalue;
}
}
The second dropdown down is not coming properly.In listener method of first dropdown the value from first drop down is not 116/118/120.
***The dbms portion is to be ignored.I had put it for another implementation.
I was able to spot several problems.
You closed your h:form just after the group of radio buttons, but continued to put other elements outside the form. Similarly, your f:view is closed right after the panel group, yet other form elements appear after this one. Just move the closing tags for your h:form and f:view right after closing tag of the last h:selectOneMenu (in this order), this should fix one part of your problem.
Both of your f:ajax are bound to click, change this to change, otherwise actions are performed even when user, for example, just opens the dropdown.
Both of your f:ajax have render defined as something starting with colon - I had to remove the colon, otherwise the elements were not found.
The "Choose your owner" dropdown's value is bound to an empty string, which is not correct. Change this to value="#{authorData.favoriteCar2}".
The method Author.getCar4List() creates a new list each time it is called. Consider keeping only return car4List; there and moving the creation to a separate method, annotated with #PostConstruct so that it is only called once:
#PostConstruct
private void init() {
car4List = new ArrayList<Car>();
car4List.add(new Car("BMW", "116"));
car4List.add(new Car("AUDI", "118"));
car4List.add(new Car("MERCEDES", "120"));
}
I hope these are all the changes I made, cannot recall there would be anything else needed.
userData definition was not part of the code you shared here, so I had to replace some of these references with authorData and remove few of them, but that should not have much impact to the things mentioned above.
I can't for the life of me figure out whats wrong with the code. I have spent some time trying to debug the issue. When i fill out the add employee form only null values are being created in the form. At this point i am stuck and need some help to get to the solution.
EmpController.java
package ejb605.controller.com;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import ejb605.assignment2.com.EmployeeManager;
import entity.Employee;
#ManagedBean
#SessionScoped
public class EmpController implements Serializable{
#EJB
EmployeeManager em;
private List<Employee> list = new ArrayList<>();
private Employee emp = new Employee();
private String empSearchID;
public List<Employee> getList() {
list = em.getAllEmployees();
return list;
}
public String getEmpSearchID() {
return empSearchID;
}
public void setEmpSearchID(String empSearchID) {
this.empSearchID = empSearchID;
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public String Search(){
this.setEmp(em.getEmployee(Integer.parseInt(this.empSearchID)));
return "EmployeeSearchDetails";
}
public String AddEmp(){
emp = em.addEmployee(this.emp);
list = em.getAllEmployees();
return "NewEmployee";
}
}
Employee.java JPA
package entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the employees database table.
*
*/
#Entity
#Table(name="employees")
#NamedQuery(name="findAllEmployees", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="department_id")
private int departmentId;
private String email;
#Column(name="first_name")
private String firstName;
#Temporal(TemporalType.DATE)
#Column(name="hire_date")
private Date hireDate;
#Column(name="last_name")
private String lastName;
#Column(name="manager_id")
private int managerId;
private String phone;
public Employee() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getDepartmentId() {
return this.departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getHireDate() {
return this.hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getManagerId() {
return this.managerId;
}
public void setManagerId(int managerId) {
this.managerId = managerId;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
package ejb605.assignment2.com;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import entity.Employee;
/**
* Session Bean implementation class EmployeeManager
*/
#Stateless
#LocalBean
public class EmployeeManager implements EmployeeManagerLocal {
#PersistenceContext(name="EmployeeJPA")
EntityManager em;
public EmployeeManager(){
}
public List<Employee> getAllEmployees() {
Query q = em.createNamedQuery("findAllEmployees",Employee.class);
return q.getResultList();
}
public Employee getEmployee(Integer id){
return em.find(Employee.class, id);
}
public void updateEmployee(Employee e){
Employee emp = getEmployee(e.getId());
emp.setFirstName(e.getFirstName());
emp.setLastName(e.getLastName());
emp.setDepartmentId(e.getDepartmentId());
emp.setEmail(e.getEmail());
emp.setHireDate(e.getHireDate());
emp.setManagerId(e.getManagerId());
emp.setPhone(e.getPhone());
em.persist(emp);
em.flush();
}
#Override
public Employee addEmployee(Employee e) {
em.persist(e);
em.flush();
return e;
}
public void deleteEmployee(Integer id) {
Employee e = em.find(Employee.class, id);
if ( e == null ) {
System.err.println("Error deleteing employee " + id);
}else {
em.remove(e);
em.flush();
}
}
}
index.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">
<h:outputText value="#{employeeSearchController}"></h:outputText>
<f:loadBundle basename="resources.application" var="msg"/>
<head>
<title><h:outputText value="#{msg.welcomeTitle}" /></title>
</head>
<body>
<CENTER><h1><b>Employee Details</b></h1></CENTER>
<h4 style="color:red">${error}</h4>
<h:form>
<fieldset style="width:=300px">
<legend>Find Employee</legend>
<table>
<tr>
<td>Employee ID:</td>
<td><h:inputText id="i1" value="#{empController.empSearchID}" label="Employee Id"></h:inputText></td>
</tr>
</table>
</fieldset>
<h:commandButton value="Search" action="#{empController.Search}" />
</h:form>
<legend>Add Employee</legend>
<h:form>
<table>
<tr>
<td>Employee ID (Key)*:</td>
<td><h:inputText id="i2" value="#{empController.emp.id}" label="EmployeeId"></h:inputText></td>
</tr>
<tr>
<td>First Name *:</td>
<td><h:inputText id="i3" value="#{empController.emp.firstName}" label="FirstName"></h:inputText></td>
</tr>
<tr>
<td>Last Name: *:</td>
<td><h:inputText id="i4" value="#{empController.emp.lastName}" label="LastName"></h:inputText></td>
</tr>
<tr>
<td> Email: </td>
<td><h:inputText id="i5" value="#{empController.emp.email}" label="email"></h:inputText></td>
</tr>
<tr>
<td> Phone: </td>
<td><h:inputText id="i6" value="#{empController.emp.phone}" label="phoneNumber"></h:inputText></td>
</tr>
<tr>
<td>Hire Date(MM/DD/yyyy):</td>
<td><h:inputText id="i7" value="#{empController.emp.hireDate}" label="hireDate"></h:inputText></td>
</tr>
<tr>
<td>Manager Id:</td>
<td><h:inputText id="i8" value="#{empController.emp.managerId}" label="Manager ID"></h:inputText></td>
</tr>
<tr>
<td>Department Id:</td>
<td><h:inputText id="i9" value="#{empController.emp.departmentId}" label="DepartmentID"></h:inputText></td>
</tr>
</table>
<h:commandButton value="Add" immediate="true" action="#{empController.AddEmp}" />
</h:form>
</body>
<h:commandButton value="update Employee" immediate="true" action="#{empController.updateEmp}" />
</html>
NewEmployee.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">
<f:loadBundle basename="resources.application" var="msg"/>
<head>
<title><h:outputText value="#{msg.welcomeTitle}" /></title>
</head>
<h:body>
<h:dataTable value="#{empController.list}" var="e" border="2">
<h:column>
<f:facet name="header">
<h:outputText value="First Name"/>
</f:facet>
<h:outputText value="#{e.firstName}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
<h:outputText value="#{e.lastName}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Email"/>
</f:facet>
<h:outputText value="#{e.email}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Phone"/>
</f:facet>
<h:outputText value="#{e.phone}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Hire Date"/>
</f:facet>
<h:outputText value="#{e.hireDate}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Manager ID"/>
</f:facet>
<h:outputText value="#{e.managerId}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Department ID"/>
</f:facet>
<h:outputText value="#{e.departmentId}"/>
</h:column>
</h:dataTable>
</h:body>
</html>
This question already has answers here:
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 8 years ago.
I am new in JSF and facing problem in getting the drop down list. I don't want to use the #PostConstructor. I tried couple of sources on google but i don't know where i am making the mistake. please hep me out.
Managed Bean
package com.employee.registration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class EmployeeBean implements Serializable {
private static final long serialVersionUID = -5400118477202860998L;
private String firstName;
private String lastName;
private String emailID;
private int employeeNumber;
private String employeeDepartment;
private String dplist;
private List<DepartmentList> departmentList;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailID() {
return emailID;
}
public void setEmailID(String emailID) {
this.emailID = emailID;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
public List<DepartmentList> getDepartmentList() {
return departmentList;
}
public void setDepartmentList(List<DepartmentList> departmentList) {
this.departmentList = departmentList;
}
public List<DepartmentList> getDepartments() {
departmentList = new ArrayList<DepartmentList>();
departmentList.add(new DepartmentList("1", "Finance"));
departmentList.add(new DepartmentList("2", "Bnking"));
return departmentList;
}
public String getDplist() {
return dplist;
}
public void setDplist(String dplist) {
this.dplist = dplist;
}
}
Java Class
package com.employee.registration;
public class DepartmentList {
private String departmentId;
private String departmentName;
public DepartmentList(String departmentId, String departmentName) {
this.departmentId = departmentId;
this.departmentName = departmentName;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
XHTML
<?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:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Employee Registration</title>
<h:outputStylesheet library="css" name="stylesheet.css" />
</h:head>
<h:body>
<h:form>
<fieldset>
<legend>Enter the Employees Information </legend>
<h:outputLabel id="firstName" value="First Name :" for="fName"></h:outputLabel>
<h:inputText id="fName" value="#{employeeBean.firstName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="lastName" value="Last Name :" for="lName"></h:outputLabel>
<h:inputText id="lName" value="#{employeeBean.lastName}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="emailId" value="Email ID :"></h:outputLabel>
<h:inputText id="email" value="#{employeeBean.emailID}"
required="true"></h:inputText>
<br></br>
<h:outputLabel id="employeeNumberId" value="Employee Number :"></h:outputLabel>
<h:inputText id="empNumber" value="#{employeeBean.employeeNumber}"></h:inputText>
<br></br>
<h:outputLabel id="employeeDepartmentID" value="Employee Department"></h:outputLabel>
<h:inputText id="eDepartment"
value="#{employeeBean.employeeDepartment}"></h:inputText>
<br></br>
<h:selectOneMenu value="#{employeeBean.dplist}"></h:selectOneMenu>
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}"></f:selectItems>
<h:commandButton id="submit" value="Submit"
action="outputInformation"></h:commandButton>
</fieldset>
</h:form>
</h:body>
</html>
selectItems tag should be inside selectOneMenu :)
<h:selectOneMenu value="#{employeeBean.dplist}}">
<f:selectItems value="#{employeeBean.departmentList}" var="e"
itemLabel="#{e.departmentId}" itemValue="#{e.departmentName}" />
</h:selectOneMenu>
see tutorial here
I'm still learning how to use Facelets and I am trying to send inputted values from a JSF page to a list in a ManagedBean and then display that information in a dataTable. I have JSF page to enter in the data, a backing bean to manage the list, and a regular application for the normal objects. I can't figure out how to send the input value from the JSF to the backing bean, however.
Here is my view:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Guestbook Form</title>
</h:head>
<h:body>
<h:form>
<h1>Guestbook Application Form</h1>
<p>Please fill out all entries and click the Submit button</p>
<h:panelGrid columns="3">
<h:outputText value = "Name: "></h:outputText>
<h:inputText id="nameInputText" required ="true"
requiredMessage="Please enter your name"
value = "#{guestbookBean.name}"
validatorMessage="Name must be fewer than 20
characters">
<f:validateLength maximum="20"/>
</h:inputText>
<h:message for="nameInputText" styleClass="error"/>
<h:outputText value = "Email: "></h:outputText>
<h:inputText id="emailInputText" required ="true"
requiredMessage="Please enter your email address"
value="#{guestbookBean.email}"
validatorMessage="Invalid email address format">
<f:validateRegex pattern ="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
</h:inputText>
<h:message for="emailInputText" styleClass="error"/>
<h:outputText value = "Enter a message: "></h:outputText>
<h:inputTextarea id="messageInputText" required ="true"
requiredMessage="Please enter a message"
value="#{guestbookBean.message}"
validatorMessage="Message must be fewer than 140 characters">
<f:validateLength maximum="140"/>
</h:inputTextarea>
<h:message for="messageInputText" styleClass="error"/>
</h:panelGrid>
<h:commandButton value="Submit" type ="Submit" action ="#{guestbookBean.setList()}"/>
<h:commandButton value ="Reset Form" type ="reset"/>
<h:outputText escape="false" value ="#{guestbookBean.result}"/>
<h:dataTable value="#{guestbookBean.list}" var="guests"
styleClass="table" cellpadding="5" cellspacing="1" border="2">
<h:column>
<f:facet name ="header">Name</f:facet>
#{guests.name}
</h:column>
<h:column>
<f:facet name ="header">Email</f:facet>
#{guests.email}
</h:column>
<h:column>
<f:facet name ="header">Message</f:facet>
#{guests.message}
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
Here is my backing bean:
package guestbook;
import java.util.List;
import java.util.ArrayList;
import java.io.Serializable;
import javax.enterprise.context.Dependent;
import javax.faces.bean.*;
#ManagedBean(name = "guestbookBean")
public class GuestbookBean implements Serializable{
private String na;
private String em;
private String m;
private List<GuestbookEntry> bookList = new ArrayList<>();
//Set name
public void setName(String first)
{
this.na = first;
}
//Set email
public void setEmail(String mail)
{
this.em = mail;
}
//Set message
public void setMessage(String msg)
{
this.m = msg;
}
//Return the name
public String getName()
{
return na;
}
//Return the email
public String getEmail()
{
return em;
}
//Return the message
public String getMessage()
{
return m;
}
public void setList()
{
GuestbookEntry bk = new GuestbookEntry();
bk.setName(na);
bk.setEmail(em);
bk.setMessage(m);
bookList.add(0, bk);
}
public List<GuestbookEntry> getList()
{
return bookList;
}
// returns result for rendering on the client
public String getResult()
{
if ( !bookList.isEmpty())
{
return "<p style=\"background-color:yellow;width:200px;" +
"padding:5px\">Data submitted successfully"+ "</p>";
}
else
{
return ""; // request has not yet been made
}
} // end method getResult
}
Here is my model:
package guestbook;
public class GuestbookEntry {
private String firstName;
private String lastName;
private String email;
private String message;
public void setFirstName(String fn)
{
firstName = fn;
}
public void setLastName(String ln)
{
lastName = ln;
}
public void setEmail(String em)
{
email = em;
}
public void setMessage(String m)
{
message = m;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getEmail()
{
return email;
}
public String getMessage()
{
return message;
}
}
The data is not being reset because you are not clearing the fields after the submit
You can set to null na, em and m to reset the fields
Regarding the table, try adding #ViewScoped to your bean, the default scope is RequestScope, which is not keeping your table