JSF selectOneMenu [duplicate] - jsf

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

Related

unable to get data from ManagedBean in JSF [duplicate]

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

How to pass selected row data from datatable between two beans [duplicate]

This question already has answers here:
Creating master-detail pages for entities, how to link them and which bean scope to choose
(2 answers)
Closed 6 years ago.
I've got a datatable with values in which I get from my DB.
In my class myBean, I've got an Variable of type User to store the selected row. It just can be selected one row. Now I want to call this Variable from an other bean which is called printUser to get the selected User.
But it always prints null.
View
<p:dataTable id="userDT" var="user" value="#{myBean.getUserList()}" selection="#{myBean.selectedUser}"
rowKey="#{user.id}" >
<p:column selectionMode="single" style="width:16px;text-align:center"/>
<p:column width="200" headerText="ID">
<h:outputText value="#{user.id}" />
</p:column>
<p:column width="200" headerText="Firstname">
<h:outputText value="#{user.firstname}" />
</p:column>
<p:column width="250" headerText="Lastname">
<h:outputText value="#{user.lastname}" />
</p:column>
</p:dataTable>
myBean
#Named(value = "myBean")
#ManagedBean
#SessionScoped
public class myBean implements Serializable {
private static final long serialVersionUID = 1L;
private User selectedUser = new User();
public myBean() {
}
public List<User> getUserList() {
...
}
public Patient getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser= selectedUser;
}
}
User.java
public class User {
private Integer id;
private String firstname;
private String lastname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
printUser
#Named(value = "printUser")
#ManagedBean
#RequestScoped
public class printUser {
public printUser() {
}
public void getSelectedUserData(){
myBean bean = new myBean();
User user = new User();
user = bean.getSelectedUser();
System.err.println("UserID: " + user.getID());
}
}
Hope you undertand my Problem.
Thanks alot
Excuse my English
This is an example to use the entity of the selected row in the same page and in another page. The example use Lombok Getter,Setter and Data annotations for shortness:
The entity for the DataTable:
#Entity
#Data
#TableGenerator( name = "GEN_TestEntity1", table = "ID_Generator", pkColumnName = "GEN_KEY", pkColumnValue = "GEN_TestEntity1", valueColumnName = "GEN_VALUE" )
#NamedQuery( name = TestEntity1.QUERY_ALL_TESTENTITY1, query = "SELECT te1 FROM TestEntity1 te1" )
public class TestEntity1 implements Serializable
{
public static final String QUERY_ALL_TESTENTITY1 = "query_All_TestEntity1";
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.TABLE, generator = "GEN_TestEntity1" )
private int id;
#Column
private String name;
}
The ManagedBean as a controller:
#ManagedBean
#SessionScoped
public class EntityBean
{
#EJB
private EntitySER entitySER;
#Getter
#Setter
private TestEntity1 selectedEntity;
public List<TestEntity1> getAllTestEntity1()
{
return entitySER.getAllTestEntity1();
}
public void onRowSelect( SelectEvent event_ )
{
}
}
Another ManagedBean which uses the first one (if you really want it):
#ManagedBean
#RequestScoped
public class AnotherBean
{
#ManagedProperty( value="#{entityBean}" )
private EntityBean entityBean;
...
}
The stateless session bean:
#Stateless
#LocalBean
public class EntitySER
{
#PersistenceContext
private EntityManager em;
public List<TestEntity1> getAllTestEntity1()
{
Query q = em.createNamedQuery( TestEntity1.QUERY_ALL_TESTENTITY1 );
return q.getResultList();
}
}
The index page (index.xhtml):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Page 1</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable id="table_TestEntity1" value="#{entityBean.allTestEntity1}" var="entity" selection="#{entityBean.selectedEntity}"
rowKey="#{entity.id}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{entityBean.onRowSelect}" update=":form:entID :form:entName"/>
<p:column>
#{entity.id}
</p:column>
<p:column>
#{entity.name}
</p:column>
</p:dataTable>
<p>
<h:outputLabel id="entID" value="#{entityBean.selectedEntity.id}"/>:
<h:outputLabel id="entName" value="#{entityBean.selectedEntity.name}"/>
</p>
<p>
<h:commandButton value="Page 2" action="/faces/another.xhtml"/>
</p>
</h:form>
</h:body>
</html>
The another Page (another.xhtml):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Another Page</title>
</h:head>
<h:body>
<p>
The selected entity: #{entityBean.selectedEntity.id}:#{entityBean.selectedEntity.name}
</p>
<h:form>
<h:commandButton value="Back" action="/faces/index.xhtml"/>
</h:form>
</h:body>
</html>

Spring Security does not redirect to landing page after succesful login via JSF form

I have a login form ,a jsf backing login bean ,and a user details service.
Although the user is authenticated he is not redirected to the landing page.
The bean authenticates the user thru the UserDetailsService w/o any problem.
package com.emredincer.yetki.bean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.security.sasl.AuthenticationException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.emredincer.yetki.entity.Kullanici;
import com.emredincer.yetki.service.IKullaniciService;
#ManagedBean(name = "loginBean")
#RequestScoped
public class LoginBean {
private String username = null;
private String password = null;
#ManagedProperty(value="#{authenticationManager}")
private AuthenticationManager authenticationManager = null;
#ManagedProperty("#{KullaniciServiceImpl}")
private IKullaniciService kullaniciServis;
private Kullanici kullanici = new Kullanici();
public String login(){
try{
Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
}
catch(Exception e){
e.printStackTrace();
return "incorrect";
}
return "correct";
}
public String logout(){
SecurityContextHolder.clearContext();
return "loggedout";
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
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 IKullaniciService getKullaniciServis() {
return kullaniciServis;
}
public void setKullaniciServis(IKullaniciService kullaniciServis) {
this.kullaniciServis = kullaniciServis;
}
public Kullanici getKullanici() {
return kullanici;
}
public void setKullanici(Kullanici kullanici) {
this.kullanici = kullanici;
}
}
<http auto-config="true">
<intercept-url pattern="/web/*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/web/login.xhtml"
authentication-success-handler-ref="successHandler"
/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="kullaniciDetayServisi" />
</authentication-manager>
</beans:beans>
public class CustomAuthSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest arg0,
HttpServletResponse arg1, Authentication arg2) throws IOException,
ServletException {
arg1.sendRedirect(arg0.getContextPath() + "/main.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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div align="center" style="">
<h:form id="loginFormId" prependId="false">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<h:outputText id="outTxtUserNameId" value="Username: " name="outTxtUserNameNm"></h:outputText>
<h:inputText id="userName" required="true" value="#{loginBean.username}" requiredMessage="Please enter username"></h:inputText>
<h:outputLabel id="outLblUserNameId" for="userName" name="outLblUserNameNm"></h:outputLabel>
</div>
<div id="loginFieldPassContId">
<h:outputText id="outTxtPasswordId" value="Password: " name="outTxtPasswordNm"></h:outputText>
<h:inputSecret id="password" required="true" value="#{loginBean.password}" requiredMessage="Please enter password" name="inTxtPasswordNm"></h:inputSecret>
<h:outputLabel id="outLblPasswordId" for="password" name="outLblPasswordNm"></h:outputLabel>
</div>
</div>
<div id="loginBtnPanelId">
<h:commandButton id="btnLoginId" value="Login" action="#{loginBean.login}" styleClass="loginPanelBtn" ajax="false"></h:commandButton>
<h:commandButton id="btnCancelId" value="Cancel" action="#{loginBean.cancel}" styleClass="loginPanelBtn" immediate="true" update="loginFormId"></h:commandButton>
</div>
</h:form>
</div>
<div>
<h:messages></h:messages>
</div>
</h:body>
</html>
i resolved the issue by modifying the login method's return statement
public String login(){
try{
Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
}
catch(Exception e){
e.printStackTrace();
return "incorrect";
}
return "/main.xhtml";
}

How to send values to a list in a backing bean and display as a dataTable

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

How to map an object in jsf from backing bean?

I am getting error while running this snippet as /facelet/crew/objectMapGossip.xhtml #14,94 value="#{objcetMapBean.searchCrewParam.staffNum}": Property 'staffNum' not readable on type java.lang.String
please help me out from this small error .. I am new to jsf so stucking at things basic ...
Thanks in advance :-)
This is my backing bean...
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "objcetMapBean")
public class ObjectMapGossip {
private SearchCrew1 searchCrewParam = new SearchCrew1("212","kart","asd");
public SearchCrew1 getSearchCrewParam() {
return searchCrewParam;
}
public void setSearchCrewParam(SearchCrew1 searchCrewParam) {
this.searchCrewParam = searchCrewParam;
}
public String search() {
return "success";
}
}
class SearchCrew1 {
public SearchCrew1() {
super();
}
/**
* #param staffNum
* #param surName
* #param rank
*/
public SearchCrew1(String staffNum, String surName, String rank) {
super();
this.staffNum = staffNum;
this.surName = surName;
this.rank = rank;
}
private String staffNum;
private String surName;
private String rank;
public String getStaffNum() {
return staffNum;
}
public void setStaffNum(String staffNum) {
this.staffNum = staffNum;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
}
This is my jsf page
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
<ui:composition template="/facelet/layout/mainlayout.xhtml">
<ui:define name="content">
<h:form>
<div align="left">
<h:outputText value="Staff Number: " />
<h:inputText id="staffnum" size="6" value="# {objcetMapBean.searchCrewParam.staffNum}" />
<h:outputText value="Surname: " />
<h:inputText id="surname" size="10" maxlength="25" value="# {objcetMapBean.searchCrewParam.surName}" />
<h:outputText value="Rank: " />
<h:inputText id="rank" size="3" value="#{objcetMapBean.searchCrewParam.rank}" />
<h:commandButton value="Search" action="#{objcetMapBean.search}" />
</div>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
We can use h:dataTable from jsf tag and map easily.
http://www.mkyong.com/jsf2/jsf-2-datatable-example/

Resources