Primefaces Picklist is always empty when using Postconstruct - jsf

My code below doesn't work, I'm using primefaces picklist and postconstruct annotation to init method with try catch block.
However my picklistbean is empty, I tried all the ways to make it work but none of them worked.
Can anyone provide me working example for picklist, or in my code am I missing something ?
I'm stuck to this problem for so long, I'll be glad if someone helps me.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import org.springframework.beans.factory.annotation.Autowired;
#ManagedBean(name = "pickListBeanTani")
#ViewScoped
public class PickListBeanTani implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<TrvrTani> tanis;
#ManagedProperty(value = "#{TrvrTaniDAO}")
private TrvrTaniDAO tanidao;
public TrvrTaniDAO getTanidao() {
return tanidao;
}
public void setTanidao(TrvrTaniDAO tanidao) {
this.tanidao = tanidao;
}
private List<TrvrTani> sourcetani;
private List<TrvrTani> targettani;
#PostConstruct
public void init(){
try {
sourcetani = new ArrayList<TrvrTani>();
targettani = new ArrayList<TrvrTani>();
tanidao = new TrvrTaniDAO();
List<TrvrTani> taniList = tanidao.findAll();
System.out.println("tanılist" +taniList);
for (TrvrTani tani : taniList) {
sourcetani.add(new TrvrTani(tani.getTaniid(), tani.getTaniadi(), tani
.getTanikodu()));
}
tanis = new DualListModel<TrvrTani>(sourcetani, targettani);
} catch (Exception e) {
throw e;
}
}
public List<TrvrTani> getSourcetani() {
return sourcetani;
}
public void setSourcetani(List<TrvrTani> sourcetani) {
this.sourcetani = sourcetani;
}
public List<TrvrTani> getTargettani() {
return targettani;
}
public void setTargettani(List<TrvrTani> targettani) {
this.targettani = targettani;
}
public DualListModel<TrvrTani> getTanis() {
return tanis;
}
public void setTanis(DualListModel<TrvrTani> tanis) {
this.tanis = tanis;
}
public void onTransferTani(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrTani) item).getTaniadi()).append("<br />");
int tanisize = tanis.getTarget().size();
System.out.println(" ************target************* : "
+ tanis.getTarget().size());
for (int h = 0; h < tanisize; h++) {
/* elemanin adi, id si ve kodu */
String taniadi = tanis.getTarget().get(h).getTaniadi();
System.out.println(" ************taniadi1************* : "
+ taniadi);
Long taniidp = tanis.getTarget().get(h).getTaniid();
System.out.println(" ************taniid2************* : "
+ taniidp);
String tanikodu = tanis.getTarget().get(h).getTanikodu();
System.out.println(" ************tanikodu3************* : "
+ tanikodu);
}
}
FacesMessage msgtani = new FacesMessage();
msgtani.setSeverity(FacesMessage.SEVERITY_INFO);
msgtani.setSummary("Tanı Eklendi");
msgtani.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgtani);
}
}

In PostContruct,your dao class doesn't inject in your bean.Try preRenderView when you want to initialize somethings in your bean.
Also dont use tanidao = new TrvrTaniDAO(); in your bean.TaniDao should be injected by spring with Autowired.
PreRenderView Example
EDIT
Also if you should inject TrvrTaniDAO with jsf managed property.
#ManagedProperty(value = "#{TrvrTaniDAO}")
private TrvrTaniDAO tanidao;

Related

Seam #Scope(ScopeType.CONVERSATION) behaves like request scoped

I am trying to implement a function where an h:commandButton component is used to produce a row of the h:dataTable with each button click. I'm testing this using a string list. When the page is first loaded, the function works fine, with the button click producing a row with value "New Item". however, when I click it the second time, the ArrayList from the ActionBean backbean seems to be reallocated. What am I doing wrong?
Action Bean:
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.ScopeType;
import jp.co.dir.bf.common.AppLogger;
import jp.co.dir.bf.front.common.BaseBean;
#Scope(ScopeType.CONVERSATION)
#Name("ActionBean")
public class ActionBean extends BaseBean {
private AppLogger appLogger;
private List<String> list = new ArrayList<String>();
public ActionBean() {
appLogger = new AppLogger(Logger.getLogger(ActionBean.class));
}
public void init(){
appLogger.showDebug("The Form is loaded");
appLogger.showDebug("Initial Size: "+ list.size());
}
public AppLogger getAppLogger() {
return appLogger;
}
public void setAppLogger(AppLogger appLogger) {
this.appLogger = appLogger;
}
public List<String> getList(){
return list;
}
public void addToList(){
list.add(new String("New Item"));
/////This is always printing 1 after each add.
appLogger.showDebug("Item added: "+ list.size());
}
public void setList(List<String> list){
this.list = list;
}
}
The xhtml:
<h:commandButton value = "Add New" >
<p:ajax listener="#{ActionBean.addToList}" update="table"/>
</h:commandButton>
<h:dataTable id = "table" value ="#{ActionBean.list}" var = "item">
<h:column>
<h:outputText value ="#{item}"/>
</h:column>
</h:dataTable>
I've fixed the issue. It's the silliness on my part. I forgot to add the
#Begin(join = true) annotation on init() so init is getting called on each load, instead of being called only once for every conversation. Hope somebody finds this helpful. The new Action Bean code is now:
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.ScopeType;
import jp.co.dir.bf.common.AppLogger;
import jp.co.dir.bf.front.common.BaseBean;
#Scope(ScopeType.CONVERSATION)
#Name("ActionBean")
public class ActionBean extends BaseBean {
private AppLogger appLogger;
private List<String> list = new ArrayList<String>();
public ActionBean() {
appLogger = new AppLogger(Logger.getLogger(ActionBean.class));
}
#Begin(join = true) ///this is the part that is updated
public void init(){
appLogger.showDebug("The Form is loaded");
appLogger.showDebug("Initial Size: "+ list.size());
}
public AppLogger getAppLogger() {
return appLogger;
}
public void setAppLogger(AppLogger appLogger) {
this.appLogger = appLogger;
}
public List<String> getList(){
return list;
}
public void addToList(){
list.add(new String("New Item"));
/////This is always printing 1 after each add.
appLogger.showDebug("Item added: "+ list.size());
}
public void setList(List<String> list){
this.list = list;
}
}

setPropertyActionListener not working after a action

I have a grid with a list of objects and I am trying to create a basic CRUD. Updates and deletes are going quite fine and without any problems, however, when I try to perform a edit on the selected object the setPropertyActionListener that I've set isn't performing as expected. I've searched on several threads but no success.
Here goes my code:
On my crud-aplicacoes.html I gotta a grid and this is the code of my button where I set my setPropertyActionListener and also my action which goes to action ="editar-aplicacao" that is another page. I'm getting my property aplicacaoSelecionada always null.
<p:commandButton icon="ui-icon-pencil"
title="#{msg['label.button.editar']}" action="editar-aplicacao"
actionListener="#{aplicacoesMB.editarAplicacao}">
<f:setPropertyActionListener
target="#{aplicacoesMB.aplicacaoSelecionada}" value="#{app}" />
</p:commandButton>
My managed bean:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import org.primefaces.model.DualListModel;
import br.com.cnen.enums.SituacaoAplicacaoeEnum;
import br.com.cnen.vo.AplicacaoVO;
import br.com.cnen.vo.PerfilVO;
import br.com.cnen.web.facade.AplicacoesFacade;
#RequestScoped
#ManagedBean(name = "aplicacoesMB")
public class AplicacoesMB extends BeanAbstract {
private static final long serialVersionUID = 1L;
private List<AplicacaoVO> listaAplicacoes;
private AplicacaoVO aplicacaoSelecionada;
private PerfilVO perfilSelecionado;
private boolean edicaoExibicao;
#Inject
private AplicacoesFacade facadeAplicacao;
private List<PerfilVO> source;
private List<PerfilVO> target;
private DualListModel<PerfilVO> dualListPerfil;
#PostConstruct
public void carregarAplicacoes() {
listaAplicacoes = facadeAplicacao.listarTodos();
this.edicaoExibicao = false;
dualListPerfil = new DualListModel<PerfilVO>();
}
public List<PerfilVO> perfis() {
return facadeAplicacao.carregarComboPerfis();
}
public List<SituacaoAplicacaoeEnum> comboStatus() {
List<SituacaoAplicacaoeEnum> lista = new ArrayList<SituacaoAplicacaoeEnum>();
for (SituacaoAplicacaoeEnum current : SituacaoAplicacaoeEnum.values()) {
lista.add(current);
}
return lista;
}
public String editarAplicacao() {
this.edicaoExibicao = false;
pickList();
return "editar-aplicacao";
}
public String visualizarAplicacao() {
this.edicaoExibicao = true;
return "editar-aplicacao";
}
public void excluirAplicacao() {
facadeAplicacao.remover(this.aplicacaoSelecionada);
this.carregarAplicacoes();
this.addMensagem("A exclusão foi realizada com sucesso.", FacesMessage.SEVERITY_INFO);
}
public void bloquearAplicacao() {
this.aplicacaoSelecionada.setSituacao(SituacaoAplicacaoeEnum.BLOQUEADO);
facadeAplicacao.bloquear(this.aplicacaoSelecionada);
this.addMensagem("O bloqueio foi realizado com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void desbloquearAplicacao() {
this.aplicacaoSelecionada
.setSituacao(SituacaoAplicacaoeEnum.DESBLOQUEADO);
facadeAplicacao.desbloquear(this.aplicacaoSelecionada);
this.addMensagem("O desbloqueio com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void alterarAplicacao(){
facadeAplicacao.alterar(aplicacaoSelecionada);
this.addMensagem("O atualização foi realizada com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void addPerfil(){
}
public void pickList(){
source = facadeAplicacao.carregarComboPerfis();
target = new ArrayList<PerfilVO>();
if(aplicacaoSelecionada!=null)
target = aplicacaoSelecionada.getListaPerfis();
dualListPerfil = new DualListModel<PerfilVO>(source, target);
}
/**
*
* Getts and setters
*
*/
public List<AplicacaoVO> getListaAplicacoes() {
return listaAplicacoes;
}
public AplicacaoVO getAplicacaoSelecionada() {
return aplicacaoSelecionada;
}
public void setAplicacaoSelecionada(AplicacaoVO aplicacaoSelecionada) {
this.aplicacaoSelecionada = aplicacaoSelecionada;
System.out.println("-> "+ aplicacaoSelecionada.getAplicaoId());
}
public PerfilVO getPerfilSelecionado() {
return perfilSelecionado;
}
public void setPerfilSelecionado(PerfilVO perfilSelecionado) {
this.perfilSelecionado = perfilSelecionado;
}
public boolean isEdicaoExibicao() {
return edicaoExibicao;
}
public List<PerfilVO> getSource() {
return source;
}
public void setSource(List<PerfilVO> source) {
this.source = source;
}
public List<PerfilVO> getTarget() {
return target;
}
public void setTarget(List<PerfilVO> target) {
this.target = target;
}
public DualListModel<PerfilVO> getDualListPerfil() {
return dualListPerfil;
}
public void setDualListPerfil(DualListModel<PerfilVO> dualListPerfil) {
this.dualListPerfil = dualListPerfil;
}
}
On my editarAplicacao() I can't access the property because it is always going null. Any thoughts on this issue?
Your concrete problem is caused by (ab)using actionListener instead of action to perform a business action. All actionListeners are invoked in the very same order as they have been attached on the component and then finally the action is invoked.
In other words, the <f:setPropertyActionListener> is in your particular case invoked after #{aplicacoesMB.editarAplicacao}, which totally explains the symptom you're seeing of the property not being set.
Fix actionListener to be action.
action="#{aplicacoesMB.editarAplicacao}"
Additionally, you can also get rid of <f:propertyActionListener> altogether and pass the property as action method argument.
action="#{aplicacoesMB.editarAplicacao(app)}"
with
public String editarAplicacao(AplicacaoVO aplicacaoSelecionada) {
// ...
}
See also:
Differences between action and actionListener
How can I pass selected row to commandLink inside dataTable?
You can replace
<f:setPropertyActionListener
target="#{aplicacoesMB.aplicacaoSelecionada}" value="#{app}" />
with
<f:attribute name="aplicacao" value="#{app}"></f:attribute>
and in your actionListenerMethod getting the attribute :
this.aplicacaoSelecionada = ((AplicacaoVO) event.getComponent().getAttributes().get("aplicacao"));

Init not being called PrimeFaces

I have an init function in my ManagedBean that is view scoped. But I can't seem to get it to run when the page loads.
Its a private field in this Class
.............
package mike.food;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.JsonMappingException;
#JsonIgnoreProperties(ignoreUnknown = true)
#ManagedBean(name = "nutrition")
#ViewScoped
public class NutritionixResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1016196967087965738L;
private String total_hits;
private String max_score;
private ArrayList<Hits> hits;
private ArrayList<Hits> droppedhits;
public NutritionixResponse() throws JsonParseException, JsonMappingException, IOException {
}
#PostConstruct
public void init() {
this.droppedhits = new ArrayList<Hits>();
}
public String getTotal_hits() {
return total_hits;
}
public void setTotal_hits(String total_hits) {
this.total_hits = total_hits;
}
public String getMax_score() {
return max_score;
}
public void setMax_score(String max_score) {
this.max_score = max_score;
}
public ArrayList<Hits> getHits() {
return hits;
}
public void setHits(ArrayList<Hits> hits) {
this.hits = hits;
}
public ArrayList<Hits> getDroppedhits() {
return droppedhits;
}
public void setDroppedhits(ArrayList<Hits> droppedhits) {
this.droppedhits = droppedhits;
}
}
The main class
#JsonIgnoreProperties(ignoreUnknown = true)
#Manaents Serializable {
gedBean(name = "FoodClient")
#ViewScoped
public class FoodClient implem
/**
* Need to test something
*/
private static final long serialVersionUID = 3874520453001209544L;
private NutritionixResponse nurition;
And the page
<p:outputPanel id="dropArea">
<p:dataTable id="droppedfoodtable" var="food"
value="#{FoodClient.nurition.droppedhits}"

I am getting a NullPointerException when trying to use the Service class

I am getting a NullPointerException which is as follows:
java.lang.NullPointerException
file:/K:/Learner/JavaFx2/ProductApplication/dist/run166129449/ProductApplication.jar!/com/product/app/view/viewsingle.fxml
at com.product.app.controller.ViewSingleController.initialize(ViewSingleController.java:70)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
And my ViewSingleController is as follows:
package com.product.app.controller;
import com.product.app.model.Product;
import com.product.app.service.ViewProductsService;
import com.product.app.util.JSONParser;
import com.product.app.util.TagConstants;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* FXML Controller class
*
* #author Arun Joseph
*/
public class ViewSingleController implements Initializable {
private static String action = "";
#FXML
private TextField txtID;
#FXML
private TextField txtName;
#FXML
private TextField txtPrice;
#FXML
private TextArea txtDesc;
#FXML
private Region veil;
#FXML
private ProgressIndicator p;
private ViewProductsService service = new ViewProductsService();
private JSONObject product = null;
private JSONParser parser = new JSONParser();
private int pid = 1;
public void setPid(int pid) {
this.pid = pid;
}
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
p.setMaxSize(150, 150);
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
Product product = new Product();
service.start();
ObservableList<Product> products = service.valueProperty().get();
products.get(pid);
txtID.textProperty().set(String.valueOf(products.get(pid).getPid()));
//product = service.valueProperty().get().get(pid);
//txtID.setText(String.valueOf(product.getPid()));
txtName.textProperty().set(product.getName());
txtPrice.textProperty().set(String.valueOf(product.getPrize()));
txtDesc.textProperty().set(product.getDescription());
}
private SomeService someService = new SomeService();
#FXML
private void handleUpdateButtonClick(ActionEvent event) {
action = "update";
someService.start();
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
}
#FXML
private void handleDeleteButtonClick(ActionEvent event) {
action = "delete";
someService.start();
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
}
#FXML
private void handleCancelButtonClick(ActionEvent event) {
closeStage();
}
private void closeStage() {
ViewSingleController.stage.close();
}
private static Stage stage = null;
public static void setStage(Stage stage) {
ViewSingleController.stage = stage;
}
private class SomeService extends Service<String> {
#Override
protected Task<String> createTask() {
return new SomeTask();
}
private class SomeTask extends Task<String> {
#Override
protected String call() throws Exception {
String result = "";
int success = 0;
List<NameValuePair> params = new ArrayList<NameValuePair>();
switch (action) {
case "update":
params.add(new BasicNameValuePair("pid", txtID.getText()));
params.add(new BasicNameValuePair("name", txtName.getText()));
params.add(new BasicNameValuePair("price", txtPrice.getText()));
params.add(new BasicNameValuePair("description", txtDesc.getText()));
product = parser.makeHttpRequest(TagConstants.url_update_product_with_id, "POST", params);
success = product.getInt(TagConstants.TAG_SUCCESS);
if (success == 1) {
result = "Successfully Updated the product";
JOptionPane.showMessageDialog(null, result);
closeStage();
}
break;
case "delete":
params.add(new BasicNameValuePair("pid", txtID.getText()));
product = parser.makeHttpRequest(TagConstants.url_delete_product_with_id, "POST", params);
success = product.getInt(TagConstants.TAG_SUCCESS);
if (success == 1) {
result = "Successfully Deleted the product";
JOptionPane.showMessageDialog(null, result);
closeStage();
}
break;
}
return result;
}
}
}
}
Please help me on how to fix this null pointer problem really help required. Thank you in advance
Inspect the line ViewSingleController.java:70. Put a breakpoint there. Run the program in a debugger and see what variables/fields are null.
The Exception happens on line 70, as you can see from the StackTrace.
On line 70, you call:
txtPrice.textProperty().set(String.valueOf(product.getPrize()));
The NullPointerException means that you are trying to access a method of an object that does not exist. Here, this might be txtPrice, textProperty, product or getPrize.
Skimming over your code, I'd guess it might be txtPrice, because you only set it as a member variable via
private TextField txtPrice;
but you never initialize it. Thus, txtPrice is null and txtPrice.textProperty().set will probably throw the NullPointer.

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