RichFaces dynamic TabPanel - jsf

How to implement a simple add/remove dynamic <rich:tabPanel>?
(I've seen people asking this around so I thought postin a Q&A of a simple implementation)

The implementation has 3 custom classes:
Content: contains the values to be displayed in a tab;
ItemTab: contais an UITab object and a Content object;
MyTabs: EJB managed bean that provides access to the tabs and adding/removal methods.
The code is:
Content:
public class Content {
String name;
String job;
String dept;
public Content() {
name = "John Doe";
job = "None";
dept = "None";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
TabItem:
public class TabItem {
UITab component;
Content content;
public TabItem() {
component = new UITab();
content = new Content();
}
public UITab getComponent() {
return component;
}
public void setComponent(UITab tab) {
this.component = tab;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
}
MyTabs:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named
#SessionScoped
public class MyTabs implements Serializable {
private List<TabItem> tabs;
public MyTabs() {
tabs = new ArrayList<TabItem>();
}
#PostConstruct
private void init() {
createTab();
createTab();
createTab();
}
public void createTab() {
TabItem tab = new TabItem();
tab.getComponent().setId("Tab" + (tabs.size()+1));
tab.getComponent().setHeader("Tab " + (tabs.size()+1));
tab.getContent().setName("John Doe " + (tabs.size()+1));
tab.getContent().setJob("Salesman " + (tabs.size()+1));
tab.getContent().setDept("Sales " + (tabs.size()+1));
tabs.add(tab);
}
public void removeTab(TabItem tab) {
tabs.remove(tab);
}
public List<TabItem> getTabs() {
return tabs;
}
public void setTabs(List<TabItem> tabs) {
this.tabs = tabs;
}
}
tabview.xhtml:
<h:commandLink value="Add Tab"
actionListener="#{myTabs.createTab()}"/>
<rich:tabPanel switchType="client">
<c:forEach items="#{myTabs.tabs}" var="tab">
<rich:tab value="#{tab.component}">
<f:facet name="header">
<h:outputLabel value="#{tab.component.header}"/>
<h:commandLink value=" X" actionListener="#{myTabs.removeTab(tab)}"/>
</f:facet>
<h:panelGrid columns="2">
<h:outputLabel value="Name: "/>
<h:outputLabel value="#{tab.content.name}"/>
<h:outputLabel value="Dept: "/>
<h:outputLabel value="#{tab.content.dept}"/>
<h:outputLabel value="Job: "/>
<h:outputLabel value="#{tab.content.job}"/>
</h:panelGrid>
</rich:tab>
</c:forEach>
</rich:tabPanel>

Related

Passing additional Objects to commandLink

I want to use the same View for different states of a bean. Therefore I need to Inject/pass/whatever get the current bean I want to modify, but I always get null.
I already tried it with , with #Inject, and the other solutions given in How can I pass selected row to commandLink inside dataTable or ui:repeat?
The View:
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import org.primefaces.PrimeFaces;
import de.auticon.beans.Mitarbeiter;
import de.auticon.beans.Skill;
#Named(value = "skillView")
#ViewScoped
public class SkillView implements Serializable {
private static final long serialVersionUID = -3256509521249071048L;
private Mitarbeiter employee;
private Skill skill = new Skill();
private List<String> expertises = new ArrayList<String>();
#PostConstruct
public void init() {
List<Expertise_String> expertiseObjects = Queries.findAllExpertises();
for (Expertise_String singleExpertise : expertiseObjects) {
expertises.add(singleExpertise.getExpertise() + " - " + singleExpertise.getFullNameString());
}
}
//Here employee is null, but I need the new/existing employee
public void addSkill() {
employee.getSkills().add(skill);
PrimeFaces.current().dialog().closeDynamic(null);
}
public void closeDialog() {
PrimeFaces.current().dialog().closeDynamic(null);
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public Mitarbeiter getEmployee() {
return employee;
}
public void setEmployee(Mitarbeiter employee) {
this.employee = employee;
}
}
XHTML from which it is called for existing employees:
<h:form id="form">
<p:panelGrid columns="2" styleClass="ui-noborder">
<p:menu toggleable="true">
<p:submenu label="Verwaltung">
<p:menuitem>
<p:commandButton value="Mitarbeiter anlegen" action="#{adminView.addNewEmployee}" icon="pi pi-users"
process="#this :form:skillsDialog">
<p:ajax event="dialogReturn" listener="#{mitarbeiterView.update}" update=":form, :form:table"/>
</p:commandButton>
</p:menuitem>
</p:submenu>
</p:menu>
<p:dataTable id="table" var="row" value="#{mitarbeiterView.mitarbeiter}" liveResize="true" resizableColumns="true">
<p:column headerText="Skillset">
<p:commandLink update=":form:skillsDialog, :form:skillsDetails" oncomplete="PF('skillsDialog').show()" title="Detail"
styleClass="ui-icon pi pi-search">
<f:setPropertyActionListener value="#{row}" target="#{mitarbeiterView.selectedEmployee}" />
</p:commandLink>
<p:commandLink action="#{adminView.openNewSkillDialog(row)}" title="add" styleClass="ui-icon pi pi-plus">
<!-- <f:setPropertyActionListener value="#{row}" target="#{skillView.employee}" /> -->
</p:commandLink>
</p:column>
</p:dataTable>
</p:panelGrid>
<p:dialog id="skillsDialog" header="Skillsheet von #{mitarbeiterView.selectedEmployee.vorname} #{mitarbeiterView.selectedEmployee.name}"
showEffect="fade" widgetVar="skillsDialog" modal="true" resizable="true">
<p:outputPanel id="skillsDetails">
<p:dataTable var="skillRow" value="#{mitarbeiterView.selectedEmployee.skills}">
<p:column headerText="Skill">
<h:outputText value="#{skillRow.name}" />
</p:column>
<p:column headerText="Ausprägung">
<h:outputText value="#{skillRow.expertise} - #{skillRow.expertiseString.fullName}" />
</p:column>
<p:column headerText="Beschreibung">
<h:outputText value="#{skillRow.description}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</p:dialog>
</h:form>
Second XHTML, for new employees:
<h:form id="newForm">
<h3>Skillsheet</h3>
<p:panelGrid id="skillPanel" columns="2" cellpadding="5" styleClass="ui-noborder">
<p:column style="width:50px">
<p:commandButton id="openAddSkill" process="#this" action="#{adminView.openNewSkillDialog}"
title="Neuer Skill" icon="pi pi-plus">
<!-- <f:setPropertyActionListener target="#{skillView.employee}" value="#{newEmployeeView.newEmployee}"/> -->
<p:ajax event="dialogReturn" update=":newForm :newForm:skillPanel"/>
</p:commandButton>
</p:column>
</p:panelGrid>
<p:commandButton value="Hinzufügen" id="addSkill" icon="pi pi-plus" action="#{skillView.addSkill()}"/>
</h:form>
AdminView.java:
#Named(value = "adminView")
#ViewScoped
public class AdminView implements Serializable {
private static final long serialVersionUID = 5252224062484767900L;
#Inject
private SkillView skillView;
public void addNewEmployee() {
Map<String, Object> options = new HashMap<String, Object>();
options.put("id", "newEmployeeDialogID");
options.put("widgetVar", "newEmployeeDialogVar");
options.put("resizable", false);
options.put("modal", false);
PrimeFaces.current().dialog().openDynamic("/dialogs/newEmployee", options, null);
}
public void openNewSkillDialog(Mitarbeiter employee) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("resizable", true);
options.put("modal", false);
options.put("contentWidth", 420);
PrimeFaces.current().dialog().openDynamic("/dialogs/skill", options, null);
skillView.setEmployee(employee);
}
}
Skill.java:
public class Skill {
#NotNull(message = "Skill fehlt")
private String name;
#NotNull(message = "Bitte Ausprägung angeben")
private short expertise;
private String description;
private String expertiseFullname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public short getExpertise() {
return expertise;
}
public void setExpertise(short expertise) {
this.expertise = expertise;
}
public String getExpertiseFullname() {
return expertiseFullname;
}
public void setExpertiseFullname(String expertiseFullname) {
this.expertiseFullname = expertiseFullname;
}
public void setExpertise(String fullName) {
try {
this.expertise = Short.valueOf(fullName.substring(0, fullName.indexOf(" - ")));
} catch (Exception e) {
this.expertise = 0;
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Mitarbeiter.java:
public class Mitarbeiter {
private int id;
#NotNull(message = "Nachname fehlt")
private String name;
#NotNull(message = "Vorname fehlt")
private String vorname;
private Date entryDate;
private List<Skill> skills = new ArrayList<Skill>();
private int expertise;
public Mitarbeiter() {
}
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 getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public List<Skill> getSkills() {
return skills;
}
public void setSkills(List<Skill> skills) {
this.skills = skills;
}
public int getExpertise() {
return expertise;
}
public void setExpertise(int expertise) {
this.expertise = expertise;
}
MitarbeiterView.java:
#Named(value = "mitarbeiterView")
#ViewScoped
public class MitarbeiterView implements Serializable {
private static final long serialVersionUID = 7924178697538784022L;
#Inject
MitarbeiterService mitarbeiterService;
private List<Mitarbeiter> mitarbeiter;
private Mitarbeiter selectedEmployee;
#PostConstruct
public void init() {
SessionConfig.initSession();
new Commons();
updateMitarbeiter();
}
private void updateMitarbeiter() {
mitarbeiter = new ArrayList<Mitarbeiter>();
List<EmployeeDTO> dtos = Queries.findAllEmployees();
for (EmployeeDTO employeeDTO : dtos) {
mitarbeiter.add(mitarbeiterService.convertToMitarbeiter(employeeDTO));
}
}
public void update() {
updateMitarbeiter();
PrimeFaces.current().ajax().update("form:table");
}
public List<Mitarbeiter> getMitarbeiter() {
return mitarbeiter;
}
public void setMitarbeiter(List<Mitarbeiter> mitarbeiter) {
this.mitarbeiter = mitarbeiter;
}
public void setSelectedEmployee(Mitarbeiter selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}
public Mitarbeiter getSelectedEmployee() {
return selectedEmployee;
}
NewEmployeeView.java:
#Named(value = "newEmployeeView")
#ViewScoped
public class NewEmployeeView implements Serializable {
private static final long serialVersionUID = 789108010781037452L;
#ManagedProperty(value = "#{mitarbeiter}")
private Mitarbeiter newEmployee = new Mitarbeiter();
#PostConstruct
public void init() {
}
public Mitarbeiter getNewEmployee() {
return newEmployee;
}
public void setNewEmployee(Mitarbeiter mitarbeiter) {
this.newEmployee = mitarbeiter;
}
Calling adSkill() from the first XHTML should have the selected employee from the Datatable. In the second case, it should have a freshly created, "empty" employee, which I already provide.
I think that major cause of your problems is that skillView bean is #RequestScoped meaning that it is being constructed and destroyed on each request and thus your employee is being reinitialized/reset to null every time. Check out this accepted answer for details.
Hints that might lead you to solution:
put debug lines in at least init() and setEmployee(..) methods of skillView and observe behaviour,
change scope of skillView to #ViewScoped which will preserve employee object across multiple Ajax requests

Error : javax.el.PropertyNotFoundException: Target Unreachable, 'null' returned null [duplicate]

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
I got this error below when I was running my JSF page.
javax.el.PropertyNotFoundException: Target Unreachable, 'null' returned null..
Warning: /createStaff.xhtml #33,125
value="#{staffBean.staff.firstName}": Target Unreachable, 'null'
returned null javax.el.PropertyNotFoundException: /createStaff.xhtml
#33,125 value="#{staffBean.staff.firstName}": Target Unreachable,
'null' returned null
I don't get why I will run into the error when I use value="#{staffBean.staff.firstName}". There is no problem when I use the value="#{staffBean.userName}" and value="#{staffBean.passWord}" above.
This is my createStaff.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:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Create Staff</title>
</h:head>
<h:body>
<f:view>
<h:form>
<p:panel id ="panel" header="Staff Creation">
<p:messages id="msgs" />
<h:panelGrid columns="3" columnClasses="label, value">
<h:outputText value="Username: *" />
<p:inputText id="username" value="#{staffBean.userName}" required="true" label="Username">
</p:inputText>
<p:message for="username" />
<h:outputLabel for="pwd1" value="Password 1: *" />
<p:password id="pwd1" value="#{staffBean.passWord}" match="pwd2" label="Password 1" required="true" feedback="true" />
<p:message for="pwd1" />
<h:outputLabel for="pwd2" value="Password 2: *" />
<p:password id="pwd2" value="#{staffBean.passWord}" label="Password 2" required="true" feedback="true" />
<p:message for="pwd2" />
<h:outputText value="First name: *" />
<p:inputText id="firstname" value="#{staffBean.staff.firstName}" required="true" label="Username">
</p:inputText>
<p:message for="firstname" />
<h:outputText value="Last name: *" />
<p:inputText id="lastname" value="#{staffBean.staff.lastName}" required="true" label="Username">
</p:inputText>
<p:message for="lastname" />
<h:outputText value="Last name: *" />
<p:selectOneRadio id="genderconsole" value="#{staffBean.staff.gender}" required="true">
<f:selectItem itemLabel="Male" itemValue="Male" />
<f:selectItem itemLabel="Female" itemValue="Female" />
</p:selectOneRadio>
<p:message for="genderconsole" />
<p:commandButton value="Create Staff"
id="ajax"
update="panel">
</p:commandButton>
</h:panelGrid>
</p:panel>
</h:form>
</f:view>
</h:body>
</html>
This is my StaffBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package managedbean;
import entities.Staff;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import sessionBean.staffSessionBeanLocal;
#Named(value = "staffBean")
#SessionScoped
//#ViewScoped
public class StaffBean implements Serializable {
#EJB
private staffSessionBeanLocal staffSession;
private String userName;
private String passWord;
private String loginStatus;
private Staff staff;
...........
////Code removed
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 getLoginStatus() {
return loginStatus;
}
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
}
This is my staff entity.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Staff extends User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String imageURL;
#ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
private List<Roles> roles = new ArrayList<Roles>();
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Staff)) {
return false;
}
Staff other = (Staff) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Staff[ id=" + id + " ]";
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
}
This is my User class which Staff class extends from.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String password;
private Timestamp joinDate;
private String userType;
private String gender;
private String email;
private String contactNo;
private String firstName;
private String lastName;
private Timestamp dOB;
private String address;
private String accountStatus;
private int numOfFailLogin;
private String maritalStatus;
private String activationCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.User[ id=" + id + " ]";
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Timestamp getJoinDate() {
return joinDate;
}
public void setJoinDate(Timestamp joinDate) {
this.joinDate = joinDate;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
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 Timestamp getdOB() {
return dOB;
}
public void setdOB(Timestamp dOB) {
this.dOB = dOB;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccountStatus() {
return accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public int getNumOfFailLogin() {
return numOfFailLogin;
}
public void setNumOfFailLogin(int numOfFailLogin) {
this.numOfFailLogin = numOfFailLogin;
}
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
}
You have no property firstName in your entity staff
UPDATE:
Looks like your staffobject is null add:
#PostConstruct
public void init() {
staff = new Stuff();
}
The error suggests that when the "firstName" is being accessed, it cannot be reached. So the "Staff" has not been constructed yet.
Add a method to your managed bean, this will resolve the issue.
#PostConstruct
public void init() {
staff= new Staff ();
}
For better understanding of why you should do it that way and not
Staff staff = new Staff();
JSF - what is the difference between #PostConstruct and direct method call from constructor?

Catching PrimeFaces's spinner value inside repeat structure

I'm using Primefaces and spinner component. My problem is that the spinner value is not set in the bean, if it's inside an iteration structure. My spinner is inside ui:repeat.
In the end, the problem is how to deal with different form controls mapping to the same property in bean.
<h:form>
<ui:repeat var="item" value="#{myBean.items}">
<p:spinner size="2" min="1" max="50" style="width:75px" value="#{cartBean.quantityToOrder}"/>
<p:commandButton value="Add to cart" action="#{cartBean.saveItemToCart(item)}" ajax="false"/>
</ui:repeat>
</h:form>
and my bean
#ManagedBean
#SessionScoped
public class CartBean extends BaseBean {
private int quantityToOrder;
//setter, getter...
//When called quantityToOrder = 0 always
public void saveItemToOrder(Item item) {
quantityToOrder IS 0.
}
}
I suspect it has to do with form submission, I have tried a form enclosing all elements in the collection and also a form enclosing any of the spinners + button. The generated client IDs are distinct for all spinners.
Any help would be appreciated.
Put a System.out.println("quantity: " + quantityToOrder) on your setQuantityToOrder(int quantityToOrder) method and will will see the problem. The value of the last spinner will prevail over the others because all the spinners are pointed to the same property (cartBean.quantityToOrder).
Try moving the quantityToOrder to the Item as follows:
<h:form id="mainForm">
<ui:repeat value="#{cartBean.items}" var="item">
<p:outputLabel value="#{item.name}: " for="sp" />
<p:spinner id="sp" size="2" min="1" max="50" style="width:75px" value="#{item.quantityToOrder}" />
<p:commandButton value="Add to cart" action="#{cartBean.saveItemToOrder(item)}" process="#this, sp" update=":mainForm:total" />
<br />
</ui:repeat>
Total: <h:outputText id="total" value="#{cartBean.quantityToOrder}" />
</h:form>
The cartBean:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class CartBean implements Serializable {
private List<CartItem> items;
private int quantityToOrder;
#PostConstruct
public void setup() {
items = new ArrayList<CartItem>();
items.add(new CartItem(1, "A"));
items.add(new CartItem(2, "B"));
items.add(new CartItem(3, "C"));
}
public void saveItemToOrder(CartItem item) {
//do whatever you want to do with the item quantity.
System.out.println("Qtd of " + item.getName() + ": " + item.getQuantityToOrder());
//to calculte the qtd of items on the cart.
quantityToOrder = 0;
for (CartItem cartItem : items) {
quantityToOrder += cartItem.getQuantityToOrder();
}
}
public List<CartItem> getItems() {
return items;
}
public void setItems(List<CartItem> items) {
this.items = items;
}
public int getQuantityToOrder() {
return quantityToOrder;
}
public void setQuantityToOrder(int quantityToOrder) {
this.quantityToOrder = quantityToOrder;
}
}
The CartItem:
import java.io.Serializable;
public class CartItem implements Serializable {
private Integer id;
private Integer quantityToOrder;
private String name;
public CartItem(Integer id, String name) {
this.id = id;
this.name = name;
quantityToOrder = 0;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getQuantityToOrder() {
return quantityToOrder;
}
public void setQuantityToOrder(Integer quantityToOrder) {
this.quantityToOrder = quantityToOrder;
}
#Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CartItem other = (CartItem) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
return true;
}
}

Prime Faces error Cannot add the same component twice

I am new to Java Server Faces. I am doing one simple login jsf application which has layout.xhtml, login.xhtml, loginbean.java, changepassword.xhtml, changepasswordbean.java. Login functions are working fine but changepassword function is causing some problem which I can't find what's the reason for error. I am getting error when clicking Clear Button in changepassword.xhtml page. If I click changepassword button a Null pointer exception have occured because I am trying to get a value(companyid) from another loginbean to changepasswordbean. After clicking back button in browser then selecting changepassword menu I am getting a error like Parent was not null, but this component not related. Sometimes menus will not be displayed. I don't know what's the problem, so any help here.
LoginBean.java
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable
{
Logger log;
#ManagedProperty(value = "loginBean")
public boolean isLoggedin;
public String username;
public String password;
public String companyid;
public boolean notloggedin;
#ManagedProperty(value = "#{tabMenu}")
private TabMenu tabMenu;
public LoginBean()
{
log=LoggerFactory.getLogger(LoginBean.class);
}
public void clear()
{
setUsername(null);
setPassword(null);
setCompanyId(null);
}
public String login()
{
setIsLoggedin(true);
setNotLoggedIn(false);
setCompanyId("companyid_1");
tabMenu.setTabMenu();
return "home";
}
public String logout()
{
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
setIsLoggedin(false);
setNotLoggedIn(true);
return "/login.xhtml?faces-redirect=true";
}
public void setUsername(String username)
{
this.username=username;
}
public String getUsername()
{
return username;
}
public void setPassword(String password)
{
this.password=password;
}
public String getPassword()
{
return password;
}
public void setIsLoggedin(boolean isloggedin)
{
this.isLoggedin=isloggedin;
}
public boolean getIsLoggedin()
{
return isLoggedin;
}
public void setNotLoggedIn(boolean notloggedin)
{
this.notloggedin=notloggedin;
}
public boolean getNotLoggedIn()
{
if(getIsLoggedin())
{
this.notloggedin=false;
}
else
this.notloggedin=true;
return notloggedin;
}
public void setCompanyId(String companyid)
{
this.companyid=companyid;
}
public String getCompanyId()
{
return companyid;
}
public TabMenu getTabMenu()
{
return tabMenu;
}
public void setTabMenu(TabMenu tabMenu)
{
this.tabMenu = tabMenu;
}
}
ChangePasswordBean.java
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedBean
#RequestScoped
public class ChangePasswordBean implements Serializable
{
Logger log;
#ManagedProperty(value = "changePasswordBean")
public String oldPassword;
public String newPassword;
public String retypePassword;
#ManagedProperty(value = "#{loginBean}")
public LoginBean lbean;
public ChangePasswordBean()
{
log=LoggerFactory.getLogger(ChangePasswordBean.class);
}
public void changePassword()
{
log.debug("Company Id: "+lbean.getCompanyId());
log.debug("User Name: "+lbean.getUsername());
boolean flag=false;
ChangePasswordDAO changepass=new ChangePasswordDAO();
if(oldPassword!=null && newPassword!=null && retypePassword!=null)
{
if(newPassword.equals(retypePassword))
{
flag=changepass.changePassword(oldPassword, newPassword,lbean.getUsername(),lbean.getCompanyId());
if(flag)
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_INFO,"Info", "Password Changed Successfully"));
}
else
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Password Not Changed"));
}
}
else
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "New Password and Retype Password didn't match"));
}
}
else
{
FacesContext.getCurrentInstance().addMessage("changepassform:btnchange", new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", "Old Password/New Password/Retype Password Should not be empty"));
}
}
public void clear()
{
setOldPassword(null);
setNewPassword(null);
setRetypePassword(null);
}
public void setOldPassword(String oldPassword)
{
this.oldPassword=oldPassword;
}
public String getOldPassword()
{
return oldPassword;
}
public void setNewPassword(String newPassword)
{
this.newPassword=newPassword;
}
public String getNewPassword()
{
return newPassword;
}
public void setRetypePassword(String retypePassword)
{
this.retypePassword=retypePassword;
}
public String getRetypePassword()
{
return retypePassword;
}
public void setLbean(LoginBean lbean)
{
this.lbean=lbean;
}
public LoginBean getLbean()
{
return lbean;
}
}
changepassword.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<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"
xmlns:p="http://primefaces.org/ui">
<body>
<ui:composition template="../templates/layout.xhtml">
<ui:define name="content">
<h:form id="changepassform" rendered="#{loginBean.isLoggedin}">
<p:messages id="messages" autoUpdate="true" redisplay="false"
showDetail="true"/>
<h:panelGrid columns="2">
<h:outputLabel value="Current Password"/>
<p:inputText value="#{changePasswordBean.oldPassword}" style="width: 106px;"/>
<h:outputLabel value="New Password"/>
<p:password value="#{changePasswordBean.newPassword}" style="width: 106px;"></p:password>
<h:outputLabel value="Retype New Password"/>
<p:inputText value="#{changePasswordBean.retypePassword}" style="width: 106px;"/>
</h:panelGrid>
<br></br>
<h:panelGrid columns="2" style="margin-left: 100px">
<h:commandButton action="#{changePasswordBean.changePassword()}" value="Change Password" id="btnchange" />
<h:commandButton action="#{changePasswordBean.clear()}" value="Clear" id="btnclear" />
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
I solved this issue by setting the transient option=true. Because I was creating menus dynamically which resulted in "WARNING: Unable to save dynamic action with clientId 'j_idt8:j_idt9:0:j_id3' because the UIComponent cannot be found" and "Cannot remove the same component twice: j_idt8:j_idt9:j_id3" problems.
public void setMenus(String type)
{
MenuItem item;
item=new MenuItem();
item.setValue("Change Password");
item.setStyle("color:black");
item.setTransient(true); /* Set this to solve the problem */
item.setUrl("/adminAccount/changepassword.xhtml");
submenus.addMenuItem(item);
}

JSF dataTable and fileUpload (fileupload issue)

Please let me know your suggestion. I want to build fileUpload with specific design and having issue with getting hold of the uploadedFile.
My design:
DataModel class:
#Named
#SessionScoped
public class NJDataModel implements Serializable {
private static final long serialVersionUID = 1L;
private String sectionName;
private UploadedFile file;
public NJDataModel(String sectionName) {
this.sectionName = sectionName;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
}
Data class:
#ManagedBean(name = "NJData")
#SessionScoped
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
private List<NJDataModel> dataModel;
#PostConstruct
public void init() {
/** defaults */
dataModel = new ArrayList<NJDataModel>();
dataModel.add(new NJDataModel("Title page"));
}
public void upload() {
System.out.println("upload method triggered");
String msg = null;
for (NJDataModel i : dataModel) {
UploadedFile file = i.getFile();
// ERROR: file is always null? so could not get hold of file
if (file != null) {
System.out.println("Uploaded file:" + file.getFileName());
msg += "file:" + file.getFileName() + "size:" + file.getSize() + ", ";
}
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg));
}
}
XHTML:
<p:dataTable var="item" value="#{NJData.dataModel}"
draggableColumns="true">
<p:column>
<p:panel>
<f:facet name="header">
<h:outputText value="#{item.sectionName}" />
</f:facet>
<p:fileUpload value="#{item.file}" mode="simple" />
</p:panel>
</p:column>
</p:dataTable>
<p:commandButton value="Submit" ajax="false"
actionListener="#{NJData.upload}" />
And finally, i need to get hold of file in method: NJData.upload() - where i always get null?
My console output:
file object:null & section name:first page
file object:null & section name:second page

Resources