primefaces autocomplete not showing in textBox - jsf

I have tried to implement the autocomplete feature in primefaces but suggestions do not show up in my textbox. Can someone show me what I'm missing. theses are codes
udateCategory.xhtml
<p:panel header="Type in Category to Edit" >
<p:outputLabel value="Category Name"/>
<p:autoComplete value="#{categoryBean.selectedCategory}"
completeMethod="#{categoryBean.completeCategory}"
var="cat"
itemLabel="#{cat.categoryName}"
itemValue="#{cat}"
converter="#{catConverter}"
forceSelection="true"/>
<p:commandButton value="Update" action="#{category.saveCategory}"/>
</p:panel>
CategoryBean
public class CategoryBean implements Serializable{
private Category selectedCategory;
/**
* Creates a new instance of CategoryBean
*/
public CategoryBean() {
}
public List<Category> completeCategory (String query){
CategoryManager manager = new CategoryManager();//an instance of the manager
List<Category> suggestions = new ArrayList<>();//an instance of list
List<Category> allCategory = new ArrayList<>(); //populate the allCategory with data fro db
allCategory = manager.getAllCategory();
//checck to see if data exist in allCategory
if(!allCategory.isEmpty()){
System.out.println("kobla : allcategory has data");
}
else
{
System.out.println("kobla: no data in alcategory");
}
for(Category cat : allCategory){
if(cat.getCategoryName().startsWith(query)){
suggestions.add(cat);
}
}
//check to see if data exists in sugestions
if (!suggestions.isEmpty()) {
System.out.println("kobla : suggestions has data");
} else {
System.out.println("kobla: no data in suggestions");
}
return suggestions;
}
/**
* #return the selectedCategory
*/
public Category getSelectedCategory() {
return selectedCategory;
}
/**
* #param selectedCategory the selectedCategory to set
*/
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
}
CategoryConverter
public class CategoryConverter implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value.trim().equals("")){
return null;
}
else{
try{
int id = Integer.parseInt(value);
List<Category> myCategory = new ArrayList<>();//
myCategory = new CategoryManager().getAllCategory();//load data fro db
for(Category cat : myCategory){
if(cat.getCategoryID() == id){
return cat;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null || value ==""){
return null;
}
else
{
return String.valueOf(((Category)value).getCategoryName());
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

this works for me
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.ViewScoped;
#ManagedBean
#ViewScoped
public class CategoryBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Category selectedCategory;
#PostConstruct
public void init(){
selectedCategory = new Category();
}
public void saveCategory(){
System.out.println("saved "+this.selectedCategory);
}
public List<Category> completeCategory(String query) {
CategoryManager manager = new CategoryManager();// an instance of the
// manager
List<Category> suggestions = new ArrayList<>();// an instance of list
List<Category> allCategory = new ArrayList<>(); // populate the
// allCategory with data
// fro db
allCategory = manager.getAllCategory();
// checck to see if data exist in allCategory
if (!allCategory.isEmpty()) {
System.out.println("kobla : allcategory has data");
} else {
System.out.println("kobla: no data in alcategory");
}
for (Category cat : allCategory) {
if (cat.getCategoryName().startsWith(query)) {
suggestions.add(cat);
}
}
// check to see if data exists in sugestions
if (!suggestions.isEmpty()) {
System.out.println("kobla : suggestions has data");
} else {
System.out.println("kobla: no data in suggestions");
}
return suggestions;
}
/**
* #return the selectedCategory
*/
public Category getSelectedCategory() {
return selectedCategory;
}
/**
* #param selectedCategory
* the selectedCategory to set
*/
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
}
and
import java.io.Serializable;
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int categoryID;
private String categoryName;
public int getCategoryID() {
return categoryID;
}
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Category(int categoryID, String categoryName) {
super();
this.categoryID = categoryID;
this.categoryName = categoryName;
}
public Category() {
super();
}
#Override
public String toString() {
return "Category [categoryID=" + categoryID + ", categoryName="
+ categoryName + "]";
}
}
and
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
#ManagedBean
#RequestScoped
public class CategoryConverter implements Converter, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value.trim().equals("")){
return null;
}
else{
try{
int id = Integer.parseInt(value);
List<Category> myCategory = new ArrayList<>();//
myCategory = new CategoryManager().getAllCategory();//load data fro db
for(Category cat : myCategory){
if(cat.getCategoryID() == id){
return cat;
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null || value ==""){
return null;
}
else
{
return String.valueOf(((Category)value).getCategoryName());
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
and
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<h:form>
<p:outputLabel value="Category Name" />
<p:autoComplete
value="#{categoryBean.selectedCategory}"
completeMethod="#{categoryBean.completeCategory}"
var="cat"
itemLabel="#{cat.categoryName}"
itemValue="#{cat}"
converter="#{categoryConverter}"
forceSelection="true" />
<p:commandButton value="Update" action="#{categoryBean.saveCategory}" />
</h:form>
</h:body>
</html>

Related

What is the best practice to Manage Facade pattern for EJB session bean?

Hello,
I would like to know the best practice for managing Facades.
The main objective of my project:
Once connected via a login system, we arrive on our account page. Depending on the status of the user (project manager or executant) we can access either the project itself as well as each of its phases (status: project manager) or phases only (status: executant).
In this project, i use entities, i created a persistence unit, and used the Facade pattern to manipulate my database.
In my Netbeans, if I do New > Sessions Bean for Entity Classes, and let say that I select Example entity, then Netbeans would generate public abstract class AbstractFacade<T> {...} with many methode and
#Stateless
public class ExampleFacade extends AbstractFacade<User> {...}
for all entities i have select. For all Facade i use one ManagerBean and i use :
#EJB
private ExampleFacade exempleFacade;
in him .
I have a problem recovering data from other bean managers because for get projet or phase i have use #RequestScope because in .xhtml get param in URL. After search on google, i understand why i can't .
For resolv my problem, i have create a general manager for all facade.
My project works perfectly but I want to know if it's the best practice and if it's secure?
I ask myself it's a question to progress in my learning of jee and jsf
This is my generalManager
package logic;
import facade.PhasesFacade;
import facade.PostesFacade;
import facade.ProjetsFacade;
import facade.UtilisateursFacade;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import model.Phases;
import model.Projets;
import model.Utilisateurs;
/**
*
* #author valibert
*/
#Named(value = "generalManager")
#SessionScoped
public class GeneralManager implements Serializable {
private Utilisateurs currentUser;
private Projets currentProjet;
private Phases currentPhase;
ArrayList<Utilisateurs> listUtilisateurs;
ArrayList<Projets> listProjets;
ArrayList<Phases> listPhases;
private String validForm;
private String mailUtil;
private String mdpUtil;
private int idProjet;
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage();
#ManagedProperty(value = "#{param.idProjet}")
private String idProjetResquest;
#EJB
private PhasesFacade phasesFacade;
#EJB
private PostesFacade postesFacade;
#EJB
private ProjetsFacade projetsFacade;
#EJB
private UtilisateursFacade utilisateursFacade;
/**
* Creates a new instance of generalManager
*/
public GeneralManager() {
}
public Utilisateurs getCurrentUser() {
return currentUser;
}
public void setCurrentUser(Utilisateurs currentUser) {
this.currentUser = currentUser;
}
public Projets getCurrentProjet() {
return currentProjet;
}
public void setCurrentProjet(Projets currentProjet) {
this.currentProjet = currentProjet;
}
public Phases getCurrentPhase() {
return currentPhase;
}
public void setCurrentPhase(Phases currentPhase) {
this.currentPhase = currentPhase;
}
public ArrayList<Utilisateurs> getListUtilisateurs() {
return listUtilisateurs;
}
public void setListUtilisateurs(ArrayList<Utilisateurs> listUtilisateurs) {
this.listUtilisateurs = listUtilisateurs;
}
public ArrayList<Projets> getListProjets() {
return listProjets;
}
public void setListProjets(ArrayList<Projets> listProjets) {
this.listProjets = listProjets;
}
public ArrayList<Phases> getListPhases() {
return listPhases;
}
public void setListPhases(ArrayList<Phases> listPhases) {
this.listPhases = listPhases;
}
public PhasesFacade getPhasesFacade() {
return phasesFacade;
}
public void setPhasesFacade(PhasesFacade phasesFacade) {
this.phasesFacade = phasesFacade;
}
public PostesFacade getPostesFacade() {
return postesFacade;
}
public void setPostesFacade(PostesFacade postesFacade) {
this.postesFacade = postesFacade;
}
public ProjetsFacade getProjetsFacade() {
return projetsFacade;
}
public void setProjetsFacade(ProjetsFacade projetsFacade) {
this.projetsFacade = projetsFacade;
}
public UtilisateursFacade getUtilisateursFacade() {
return utilisateursFacade;
}
public void setUtilisateursFacade(UtilisateursFacade utilisateursFacade) {
this.utilisateursFacade = utilisateursFacade;
}
public String getValidForm() {
return validForm;
}
public void setValidForm(String validForm) {
this.validForm = validForm;
}
public String getMailUtil() {
return mailUtil;
}
public void setMailUtil(String mailUtil) {
this.mailUtil = mailUtil;
}
public String getMdpUtil() {
return mdpUtil;
}
public void setMdpUtil(String mdpUtil) {
this.mdpUtil = mdpUtil;
}
public String getIdProjetResquest() {
return idProjetResquest;
}
public void setIdProjetResquest(String idProjetResquest) {
this.idProjetResquest = idProjetResquest;
}
public int getIdProjet() {
return idProjet;
}
public void setIdProjet(int idProjet) {
this.idProjet = idProjet;
}
//Méthode
public String submitFormLogin(){
currentUser = utilisateursFacade.findOne(mailUtil);
if ((utilisateursFacade.findOne(mailUtil).getMdpUtil().equals(mdpUtil)) && (utilisateursFacade.findOne(mailUtil).getMailUtil().equals(mailUtil)) ){
currentUser = utilisateursFacade.findOne(mailUtil);
validForm = "toCompteFromIndex";
return validForm;
}
currentUser = new Utilisateurs();
message.setSeverity(FacesMessage.SEVERITY_INFO);
message.setSummary("L'utilisateur ou le mot de passe n'est pas valide merci de rééssayer");
message.setDetail("Message detail.");
context.addMessage("formConnection", message);
validForm = "";
return validForm;
}
public void onload(){
try {
idProjet = Integer.parseInt(idProjetResquest);
currentProjet = projetsFacade.findByIdAndUserManager(idProjet, currentUser.getIdUtil());
} catch (NumberFormatException e){
idProjetResquest = "404";
}
}
#PostConstruct
public void initUtilisateurs(){
this.listUtilisateurs = new ArrayList();
this.listUtilisateurs.addAll(utilisateursFacade.findAll());
}
}
and this is a view for example
<ui:composition template="/templates.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<f:metadata>
<f:viewParam id="idProjet" name="idProjet" value="#{generalManager.idProjetResquest}" required="true" />
<f:viewAction action="#{generalManager.onload}" />
</f:metadata>
<ui:define name="content-main">
<h2>Chef Projet #{generalManager.currentUser.prenomUtil}</h2>
<h2>Projet #{generalManager.currentProjet.libelleProj}</h2>
<p>Date du début du projet :<h:outputText value="#{generalManager.currentProjet.dateDebutProj}" >
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:outputText></p>
<p>Phases du projet</p>
<ul>
<ui:repeat value="#{generalManager.phasesFacade.findPhaseByProjet(projetsManager.projetChoose.idProjet)}" var="itemPhase">
<li>
<h:outputLink value="../phases/View.xhtml" >
<f:param name="idPhase" value="#{itemPhase.idPhase}" />
<h:outputText value="#{itemPhase.libellePhase}"/>
</h:outputLink>
</li>
</ui:repeat>
</ul>
</ui:define>
thank you in advance

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?

p:selectManyMenu report validation error (illegal select options) [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I use primefaces's p:selectManyMenu. When I submit the value, it always report validation error Illegal selection options. Can you help to solve this issue?
JSF code:
<h:outputLabel for="scenario" value="GivenStories:" />
<p:selectManyMenu id="givenstoryselect" value="#{anotherDynaFormController.selectedGivenStory}" converter="scenarioConverter" var="g" style="width:500px;height:70px;align:left;" showCheckbox="true" >
<f:selectItems value="#{anotherDynaFormController.givenStorys}" var="scenario" itemLabel="#{scenario.name}" itemValue="#{scenario}" />
<p:column>#{g.name}</p:column>
</p:selectManyMenu>
Bean class:
//converter
#FacesConverter(value="scenarioConverter")
public class ScenarioConverter implements Converter {
public static List<Scenario> scenarioDB = new ArrayList<Scenario>();
private ScenarioDao scenarioDao = new ScenarioDao();
public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
if (submittedValue.trim().equals("")) {
return null;
} else {
try {
int number = Integer.parseInt(submittedValue);
scenarioDB = scenarioDao.findAll();
for (Scenario p : scenarioDB) {
if (p.getId() == number) {
return p;
}
}
} catch(NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid scenario"));
}
}
return null;
}
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if (value == null) {
return null;
} else {
return String.valueOf(((Scenario) value).getId());
}
}
}
#ManagedBean
#ViewScoped
public class AnotherDynaFormController extends SuperBean implements Serializable {
private List<Scenario> givenStorys;
private List<Meta> selectedMetas;
private List<Scenario> selectedGivenStory;
private List<ProjectTree> parents;
public DynaFormModel getModel() {
givenStorys = scenarioDao.findAll();
...
}
...
}
Try this generic converter and see if problem still there .
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
#FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {
private static Map<Object, String> entities = new WeakHashMap<Object, String>();
#Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
synchronized (entities) {
if (!entities.containsKey(entity)) {
String uuid = UUID.randomUUID().toString();
entities.put(entity, uuid);
return uuid;
} else {
return entities.get(entity);
}
}
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
for (Entry<Object, String> entry : entities.entrySet()) {
if (entry.getValue().equals(uuid)) {
return entry.getKey();
}
}
return null;
}
}
thanks a lot. I have find the reason of this issue. I should overwrite the equals and hashcode method in this object. Then it works.
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Scenario))
return false;
return ((Scenario)obj).getId().equals(this.id);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + name.hashCode();
}

Pass Object value in Primefaces SelectOneMenu

Hello i am Using PrimeFaces 4.0 and i need to pass object value in SelectOneMenu.
I am using converter to convert that from string format to Class object format.
These are the code files please help me...
lablevalue.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
</h:head>
<h:body>
<h:form id="myform">
<p:growl showDetail="true"></p:growl>
<p:selectOneMenu value="#{itemlableAcction.idCard}" >
<f:converter converterId="converter.SelectMenUConverter" />
<f:selectItem itemLabel="Select" itemValue="" />
<f:selectItems value="#{itemlableAcction.idCards}" var="idv" itemLabel="#{idv.name}" itemValue="#{idv}" />
</p:selectOneMenu>
<h:commandButton action="#{itemlableAcction.onclickSubmit}" value="Submit"></h:commandButton>
</h:form>
</h:body>
</html>
ItemlableAcction
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import bo.IdCard;
#ManagedBean
public class ItemlableAcction {
List<IdCard> idCards = new ArrayList<IdCard>();
IdCard idCard;
public Object getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
}
public List<IdCard> getIdCards() {
return idCards;
}
public void setIdCards(List<IdCard> idCards) {
this.idCards = idCards;
}
public ItemlableAcction() {
IdCard card1 = new IdCard();
card1.setId(1);
card1.setName("ABC");
card1.setAddress("USA");
idCards.add(card1);
IdCard card2 = new IdCard();
card2.setId(2);
card2.setName("MNO");
card2.setAddress("INDIA");
idCards.add(card2);
IdCard card3 = new IdCard();
card3.setId(3);
card3.setName("XYZ");
card3.setAddress("Chaina");
idCards.add(card3);
}
public String onclickSubmit() {
IdCard ic = (IdCard) idCard;
System.out.println("In action id values are " + ic.getId() + " " + ic.getAddress());
return "";
}
}
SelectMenUConverter
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import bo.IdCard;
#FacesConverter("converter.SelectMenUConverter")
public class SelectMenUConverter implements Converter {
public SelectMenUConverter() {
System.out.println("Inside converter");
}
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
System.out.println("One" + arg2);
IdCard idCard = new IdCard(arg2);
return idCard;
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
System.out.println("Two" + value);
return value.toString();
}
}
Idcard
public class IdCard {
String name;
int id;
String address;
public IdCard() {
}
public IdCard(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Imagine you have to implement converter for 100 classes.
If you don't want to implement a own Converter and get the data from exiting list, use:
SelectItems Converter Omnifaces
You have a complete example.
PD: Don't forget to implement toString with a unique id.(See documentation)
You're not searching and getting the required instance from the defined list (in your managed-bean) when getting its identifiant through getAsObject()'s method. You're just instanciating an additional new object through the converter. Try this:
#FacesConverter("converter.SelectMenUConverter")
public class SelectMenUConverter implements Converter {
...
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
if (arg2 == null || arg2.isEmpty()) {return null;}
try {
return findIdCard(arg2); // here's where should be retreived the desired selected instance
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(("This is not a valid card id")), e);
}
}
...
public IdCard findIdCard(String id) {
Iterator<IdCard> iterator = idCards.iterator(); // "idCards" represents your idCards' list. It is not recognized yet in the converter
while(iterator.hasNext()) {
IdCard idc = iterator.next();
if(idc.getId() == Integer.valueOf(id).intValue()) {
return idc;
}
}
return null;
}

JSF: method not found

I'm getting this error while developping my application
javax.el.MethodNotFoundException: /test.xhtml #18,99
action="#{ComplexeController.saveComplexe}": Method not found:
fr.code.parc.controller.ComplexeController#97aead.saveComplexe()
test.xhtml :
<h:body>
<h1>Génération des Complexes</h1>
<h:form>
Nom Complexe: <h:inputText value="#{ComplexeController.complexe.nomComp}"/><br/>
Nom Zone: <h:selectOneMenu id="nomZone" value="#{ComplexeController.complexe.zoneParc}" converter="#{GenericConverter}">
<f:selectItems value="#{ZoneController.remplireItem()}"/>
</h:selectOneMenu>
<br/>
<h:commandButton action="#{ComplexeController.saveComplexe}" value="Insérer un nouveau complexe"/>
<h:commandButton action="#{ComplexeController.updateComplexe}" value="Modifier un complexe"/>
<br/>
<h:commandLink action="complexe" value="acceuil"/>
</h:form>
</h:body>
the entity Complexe.java
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Complexe generated by hbm2java
*/
#Entity
#Table(name="COMPLEXE"
,schema="PROJET"
)
public class Complexe implements java.io.Serializable {
private String nomComp;
private ZoneParc zoneParc;
private Set<Parc> parcs = new HashSet<Parc>(0);
public Complexe() {
}
public Complexe(String nomComp) {
this.nomComp = nomComp;
}
public Complexe(String nomComp, ZoneParc zoneParc, Set<Parc> parcs) {
this.nomComp = nomComp;
this.zoneParc = zoneParc;
this.parcs = parcs;
}
#Id
#Column(name="NOM_COMP", unique=true, nullable=false, length=30)
public String getNomComp() {
return this.nomComp;
}
public void setNomComp(String nomComp) {
this.nomComp = nomComp;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="NOM_ZONEE")
public ZoneParc getZoneParc() {
return this.zoneParc;
}
public void setZoneParc(ZoneParc zoneParc) {
this.zoneParc = zoneParc;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="complexe")
public Set<Parc> getParcs() {
return this.parcs;
}
#Override
public int hashCode() {
int hash = 0;
hash += (nomComp != null ? nomComp.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 Complexe)) {
return false;
}
Complexe other = (Complexe) object;
if ((this.nomComp == null && other.nomComp != null) || (this.nomComp != null && !this.nomComp.equals(other.nomComp))) {
return false;
}
return true;
}
public void setParcs(Set<Parc> parcs) {
this.parcs = parcs;
}
}
and now ComplexeDaoImpl.java
import config.HibernateUtil;
import fr.code.parc.model.Complexe;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* #author raddaouirami
*/
public class ComplexeDaoImpl implements ComplexeDao{
#Override
public List<Complexe> list() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
List complexes = session.createQuery("from Complexe").list();
t.commit();
return complexes;
}
#Override
public Complexe getComplexe(String nomComp) {
Session session = HibernateUtil.getSessionFactory().openSession();
return (Complexe) session.load(Complexe.class, nomComp);
}
#Override
public void save(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.save(complexe);
t.commit();
}
#Override
public void update(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.update(complexe);
t.commit();
}
#Override
public void remove(Complexe complexe) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.delete(complexe);
t.commit();
}
}
and Finally ComplexeController.java
import fr.code.parc.dao.ComplexeDao;
import fr.code.parc.dao.ComplexeDaoImpl;
import fr.code.parc.model.Complexe;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
/**
*
* #author raddaouirami
*/
#ManagedBean
#SessionScoped
public class ComplexeController {
private Complexe complexe;
private DataModel listeComplexes;
private int selectedItemIndex;
/**
* Creates a new instance of ComplexeController
*/
public ComplexeController() {
complexe = new Complexe();
}
/* public Complexe getSelected() {
if (complexe == null) {
complexe = new Complexe();
selectedItemIndex = -1;
}
return complexe;
}*/
public DataModel getListeComplexes() {
List<Complexe> liste = new ComplexeDaoImpl().list();
listeComplexes = new ListDataModel(liste);
return listeComplexes;
}
/**
* #return the complexe
*/
public Complexe getComplexe() {
return complexe;
}
/**
* #param complexe the complexe to set
*/
public void setComplexe(Complexe complexe) {
this.complexe = complexe;
}
public String preparationAddComplexe(){
setComplexe(new Complexe());
return "test";
}
public String preparationEditComplexe(){
setComplexe((Complexe)(getListeComplexes().getRowData()));
return "test";
}
public String DeleteComplexe(){
Complexe complexes = (Complexe)(getListeComplexes().getRowData());
ComplexeDao dao = new ComplexeDaoImpl();
dao.remove(complexes);
return "complexe";
}
public String SaveComplexe(){
ComplexeDao dao = new ComplexeDaoImpl();
dao.save(getComplexe());
return "complexe";
}
public String UpdateComplexe(){
ComplexeDao dao = new ComplexeDaoImpl();
dao.update(complexe);
return "complexe";
}
}
How can I solve it?
In view you invoke saveComplexe
action="#{ComplexeController.saveComplexe}"
ComplexeController has only SaveComplexe method.
Either change to
action="#{ComplexeController.SaveComplexe}"
or rename method in ComplexeController to saveComplexe
2 Solutions:
Solution 1.
Change in test.xhtml : complexeController.saveComplexe [Notice first letter in complexeController is in smaller case]
<h:commandButton action="#{complexeController.saveComplexe}" value="Insérer un nouveau complexe"/>
<h:commandButton action="#{complexeController.updateComplexe}" value="Modifier un complexe"/>
Solution 2.
Change in ComplexeController.java:
#ManagedBean(name="ComplexeController ")
#SessionScoped
public class ComplexeController {
....
}
Read the Following Info about Configuring ManagedBeans in JSF:
There are 2 ways to use #ManagedBean to expose a Java Bean class to Managed Bean class.
Way 1.
#ManagedBean
public class ComplexeController{
....
}
In this case the bean exposed with same name but the first letter is smaller case, i.e., you can access the bean in Facelet as
#{complexeController}
Way 2.
#ManagedBean(name="myBean")
public class ComplexeController{
....
}
In this case the bean exposed with same name but the first letter is smaller case, i.e., you can access the bean in Facelet as
#{myBean}
Try to access the ManagedBean with first char to low case
e.g.
action="#{complexeController.saveComplexe}"
instead of
action="#{ComplexeController.saveComplexe}"

Resources