p:selectonemenu produces an extra null option and converter fails - jsf

I have a problem with p:selectonemenu. Server Logs and my codes are below.
The problem: I try to code a simple application with CRUD functionality.
h:selectonemenu works as expected. But when I switch to p:selectonemenu I get converter exception.
Normally my options data includes 3 rows in database. I made options printed after initilization as debug purpose, my list is initilized with there elements as normal.
However with p:selectmenu, my list is initialized with there elements as again (proved by syso in the init function.), but an extra selectonemenu option,null one reaches to converter. And it fires exception.
I debugged the application and saw the extra null object there too. My converter is called 3 times with h:selectonemenu, at least 4 times with p:selectmenu.
I could have made a mistake. But is this my mistake or what else?
Glassfish 3.1.2, PM 3.3.1
Server Log (h:selectmenu):
INFO: Hibernate:
select
grup0_.grup_id as grup1_8_,
grup0_.grup_adi as grup2_8_
from
Grup grup0_
INFO: Selectonemenu Option#Init :Test Value 1
INFO: Selectonemenu Option#Init :Test Value 2
INFO: Selectonemenu Option#Init :Test Value 3
INFO: Selectonemenu Option#Converter :Test Value 1
INFO: Selectonemenu Option#Converter :Test Value 2
INFO: Selectonemenu Option#Converter :Test Value 3
Server Log (p:selectmenu):
INFO: Hibernate:
select
grup0_.grup_id as grup1_8_,
grup0_.grup_adi as grup2_8_
from
Grup grup0_
INFO: Selectonemenu Option#Init :Test Value 1
INFO: Selectonemenu Option#Init :Test Value 2
INFO: Selectonemenu Option#Init :Test Value 3
INFO: Selectonemenu Option#Converter :Test Value 1
INFO: Selectonemenu Option#Converter :Test Value 2
INFO: Selectonemenu Option#Converter :Test Value 3
INFO: Hibernate:
select
grup0_.grup_id as grup1_8_,
grup0_.grup_adi as grup2_8_
from
Grup grup0_
INFO: Selectonemenu Option#Init :Test Value 1
INFO: Selectonemenu Option#Init :Test Value 2
INFO: Selectonemenu Option#Init :Test Value 3
INFO: Selectonemenu Option#Converter :Test Value 1
INFO: Selectonemenu Option#Converter :Test Value 2
INFO: Selectonemenu Option#Converter :Test Value 3
**INFO: Selectonemenu Option#Converter :null**
SEVERE: Error Rendering View[/NewFile.xhtml]
javax.faces.convert.ConverterException: getAsString Error
at converters.GrupConverter.getAsString(GrupConverter.java:60)
at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:76)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeLabel(SelectOneMenuRenderer.java:120)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeMarkup(SelectOneMenuRenderer.java:89)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeEnd(SelectOneMenuRenderer.java:62)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
javax.faces.convert.ConverterException: getAsString Error
at converters.GrupConverter.getAsString(GrupConverter.java:60)
at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:76)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeLabel(SelectOneMenuRenderer.java:120)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeMarkup(SelectOneMenuRenderer.java:89)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeEnd(SelectOneMenuRenderer.java:62)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
test.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<body>
<h:form>
<p:selectOneMenu id="grup" value="#{grupBean.grup}" converter="grupConverter">
<f:selectItems value="#{grupBean.grupList}" var="grp" itemLabel="#{grp.grup_adi}" itemValue="#{grp}" />
</p:selectOneMenu>
</h:form>
</body>
</html>
Grup.java
package model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Grup implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8730335332086520080L;
#Id
#GeneratedValue
private Integer grup_id;
private String grup_adi;
#ManyToMany(mappedBy="gruplar")
private List<Kullanici> kullanicilar = new ArrayList<Kullanici>();
public Integer getGrup_id() {
return grup_id;
}
public void setGrup_id(Integer grup_id) {
this.grup_id = grup_id;
}
public String getGrup_adi() {
return grup_adi;
}
public void setGrup_adi(String grup_adi) {
this.grup_adi = grup_adi;
}
public List<Kullanici> getKullanicilar() {
return kullanicilar;
}
public void setKullanicilar(List<Kullanici> kullanicilar) {
this.kullanicilar = kullanicilar;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((grup_id == null) ? 0 : grup_id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Grup))
return false;
Grup other = (Grup) obj;
if (grup_id == null) {
if (other.grup_id != null)
return false;
} else if (!grup_id.equals(other.grup_id))
return false;
return true;
}
}
GrupConverter.java
package converters;
import model.Grup;
import javax.faces.application.FacesMessage;
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;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.persistence.EntityManager;
import util.EntityUtil;
#FacesConverter(value = "grupConverter")
public class GrupConverter implements Converter {
EntityManager em = EntityUtil.getEntityManager();
#Override
public Object getAsObject(FacesContext context, UIComponent component,
String deger) {
Grup findGrup = null;
if (deger == null || deger.isEmpty()) {
return null;
}
try {
findGrup = em.find(Grup.class, Integer.parseInt(deger));
// System.out.println(findGrup.);
} catch (Exception e) {
throw new ConverterException(new FacesMessage(String.format(
"Cannot convert %s to Grup", deger)), e);
}
return findGrup;
}
#Override
public String getAsString(FacesContext context, UIComponent component,
Object deger) {
String val = null;
// ....................
Grup d = (Grup) deger;
System.out
.println("Selectonemenu Option#Converter :" + d.getGrup_adi());
// .....................
try {
Grup b = (Grup) deger;
val = Integer.toString(b.getGrup_id());
} catch (Exception e) {
throw new ConverterException(new FacesMessage("getAsString Error"));
}
return val;
}
}
GrupBean.java
package beans;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import model.Birim;
import model.Grup;
import util.EntityUtil;
#ManagedBean
#ViewScoped
public class GrupBean implements Serializable{
private static final long serialVersionUID = 2166603645975073743L;
List<Grup> grupList=null;
List<Birim> birimList;
EntityManager em = EntityUtil.getEntityManager();
private boolean edit;
Grup grup=new Grup();
#PostConstruct
public void init()
{
grupList = em.createQuery("from Grup").getResultList();
//birimList=em.createQuery("from Birim").getResultList();
for (Grup grup : grupList) {
System.out.println("Selectonemenu Option#Init :"+grup.getGrup_adi());
}
}
public void add()
{
System.out.println("Add");
em.getTransaction().begin();
em.persist(grup);
em.getTransaction().commit();
System.out.println("End of Add");
grupList = em.createQuery("from Grup").getResultList();
edit = false;
grup = new Grup(); // Reset placeholder.
}
public void edit(Grup grup) {
this.grup = grup;
//System.out.println("Grup Edit"+grup.anAdi());
edit = true;
}
public void save() {
// dao.update(item);
System.out.println("save");
em.getTransaction().begin();
em.merge(grup);
em.getTransaction().commit();
System.out.println("End of save");
edit = false;
grupList = em.createQuery("from Grup").getResultList();
grup = new Grup(); // Reset placeholder.
}
public void delete(Grup grup) {
System.out.println("delete");
em.getTransaction().begin();
em.remove(grup);
em.getTransaction().commit();
System.out.println("End of delete");
grup = new Grup(); // Reset placeholder.
edit = false;
grupList = em.createQuery("from Grup").getResultList();
}
public List<Grup> getGrupList() {
return grupList;
}
public void setGrupList(List<Grup> grupList) {
this.grupList = grupList;
}
public Grup getGrup() {
return grup;
}
public void setGrup(Grup grup) {
this.grup = grup;
}
public boolean isEdit() {
return edit;
}
public List<Birim> getBirimList() {
return birimList;
}
public void setBirimList(List<Birim> birimList) {
this.birimList = birimList;
}
}

Related

javax.el.ELException: Property 'askQuestiοn' not found on type trainforjava.domain.Questiοn [duplicate]

This question already has answers here:
javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean
(6 answers)
Closed 6 years ago.
My problem is the following. I've a list which i s well created, but I can't manage to display it on my web page.
Here is the pojo :
package trainforjava.domain;
public class Question {
public int id;
public String askedQuestion;
public String proposal;
public Question() {
super();
}
public Question(int id, String askedQuestion, String proposal) {
super();
this.id = id;
this.askedQuestion = askedQuestion;
this.proposal = proposal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setAskedQuestion(String askedQuestion) {
this.askedQuestion = askedQuestion;
}
public String getAskedQuestion() {
return askedQuestion;
}
public void setQuestion(String askedQuestion) {
this.askedQuestion = askedQuestion;
}
public String getProposal() {
return proposal;
}
public void setProposal(String proposal) {
this.proposal = proposal;
}
#Override
public String toString() {
return "Question [id=" + id + ", askedQuestion=" + askedQuestion + "]";
}
}
Here is the managed bean :
package trainforjava.domain;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import trainforjava.util.QuestionCreator;
#ManagedBean
public class QuestionBean {
public List<String> proposals;
public List<Question> questions;
public QuestionCreator creator = new QuestionCreator();
public QuestionBean() {
System.out.println("beforecreate");
questions = creator.createQuestions();
System.out.println(questions);
// proposals = creator.createProposals(0);
}
public List<String> getProposals() {
return proposals;
}
public void setProposals(List<String> proposals) {
this.proposals = proposals;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
}
Here is the pojo creating from a properties file :
package trainforjava.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.stereotype.Component;
import trainforjava.domain.Question;
public class QuestionCreator {
List<Question> questions =new ArrayList<Question>();
List<String> proposals = new ArrayList<String>();
public List<Question> createQuestions() {
final Properties properties = new Properties();
InputStream input = null;
System.out.println("createQuestions");
try {
input = getClass().getResourceAsStream("/questions.properties");
// load a properties file
properties.load(input);
// get the property value and print it out
for (int i = 0; i < properties.size(); i++) {
Question question = new Question();
StringBuilder sb = new StringBuilder();
sb.append("question-").append(i);
String askedQuestion = properties.getProperty(sb.toString());
question.setAskedQuestion(askedQuestion);
question.setId(i);
questions.add(question);
}
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
return questions;
}
public List<String> createProposals(int key) {
final Properties properties = new Properties();
InputStream input = null;
System.out.println("createProposals");
try {
input = getClass().getResourceAsStream("/proposals.properties");
// load a properties file
properties.load(input);
for(int i =0 ; i < proposals.size(); i++){
int idQuestion = key;
System.out.println("createProposals id" + idQuestion);
StringBuilder sb = new StringBuilder();
sb.append("proposal-").append(idQuestion).append("-").append(i);
String proposal = properties.getProperty(sb.toString());
proposals.add(proposal);
System.out.println(proposals);
}
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
return proposals;
}
}
The console print me the list created, which name is "questions", but also print me a stacktrace :
beforecreate
createQuestions
[Question [id=0, askedQuestion=Quelle interface est implémentée par la Classe ArrayList ?], Question [id=1, askedQuestion=Quelle interface est implémentée par la Classe HashMap ?], Question [id=2, askedQuestion=Quelle interface est implémentée par la Classe Vector ?]]
août 23, 2016 2:29:19 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
GRAVE: Error Rendering View[/index.xhtml]
javax.el.ELException: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:161)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
août 23, 2016 2:29:19 AM com.sun.faces.context.ExceptionHandlerImpl log
1100: JSF1073 : javax.el.ELException intercepté durant le traitement de RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=/index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
août 23, 2016 2:29:19 AM com.sun.faces.context.ExceptionHandlerImpl log
1100: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
javax.el.ELException: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:161)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
And then, the index.xhtml which is supposed to display this list :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Test</title>
</h:head>
<h:body>
Question :
<h:form>
<h:dataTable value="#{questionBean.questions}" var="question">
<h:column>
#{question.askQuestion}
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
Can someone help me please ?
The property name is actually askedQuestion, and not askQuestion.

Class Not Found Error in a refactor-moved JSF Managed Bean

I re factor and move JSF managed bean from one package to another package in Netbeans JSF application. Intermittently I get an error stating that the moved bean is not found in the previous location. I clean and build several times. Still the issue persists. I restarted the GlassFish and even the computer. I find in project including the generate sources, but I could not locate any reference to that Bean. I add the current location to the faces-config.xml, still no result.
The Previous Package is com.divudi.bean
New Package is com.divudi.bean.lab
The Error Message is
SEVERE: Exception while loading the app : com/divudi/bean/CollectingCentreController
java.lang.NoClassDefFoundError: com/divudi/bean/CollectingCentreController
at java.lang.Class.getDeclaringClass(Native Method)
at java.lang.Class.getEnclosingClass(Class.java:1107)
at java.lang.Class.getSimpleBinaryName(Class.java:1242)
at java.lang.Class.isMemberClass(Class.java:1232)
at org.jboss.weld.util.reflection.Reflections.isNonStaticInnerClass(Reflections.java:139)
at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:78)
at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:123)
at org.jboss.weld.bootstrap.BeanDeployment.createBeans(BeanDeployment.java:184)
at org.jboss.weld.bootstrap.WeldBootstrap.deployBeans(WeldBootstrap.java:350)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:179)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:277)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:460)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassNotFoundException: com.divudi.bean.CollectingCentreController
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
... 41 more
The Bean is (Before Adding to faces-config.xml, where annotation is used)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.divudi.bean.lab;
import com.divudi.bean.SessionController;
import com.divudi.bean.UtilityController;
import com.divudi.data.InstitutionType;
import com.divudi.entity.Institution;
import com.divudi.facade.InstitutionFacade;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
/**
*
* #author www.divudi.com
*/
#ManagedBean
public class CollectingCentreController {
/**
* Creates a new instance of CollectingCentreController
*/
public CollectingCentreController() {
}
private static final long serialVersionUID = 1L;
#ManagedProperty(value = "#{sessionController}")
SessionController sessionController;
#EJB
private InstitutionFacade ejbFacade;
List<Institution> selectedItems;
private Institution current;
private List<Institution> items = null;
String selectText = "";
public List<Institution> getSelectedItems() {
selectedItems = getFacade().findBySQL("select c from Institution c where c.retired=false and i.institutionType = com.divudi.data.InstitutionType.CollectingCentre and upper(c.name) like '%" + getSelectText().toUpperCase() + "%' order by c.name");
return selectedItems;
}
public void prepareAdd() {
current = new Institution();
current.setInstitutionType(InstitutionType.CollectingCentre);
}
public void setSelectedItems(List<Institution> selectedItems) {
this.selectedItems = selectedItems;
}
public String getSelectText() {
return selectText;
}
private void recreateModel() {
items = null;
}
public void saveSelected() {
if (getCurrent().getId() != null && getCurrent().getId() > 0) {
getFacade().edit(current);
UtilityController.addSuccessMessage("savedOldSuccessfully");
} else {
current.setCreatedAt(Calendar.getInstance(TimeZone.getTimeZone("IST")).getTime());
current.setCreater(sessionController.getLoggedUser());
getFacade().create(current);
UtilityController.addSuccessMessage("savedNewSuccessfully");
}
recreateModel();
getItems();
}
public void setSelectText(String selectText) {
this.selectText = selectText;
}
public InstitutionFacade getEjbFacade() {
return ejbFacade;
}
public void setEjbFacade(InstitutionFacade ejbFacade) {
this.ejbFacade = ejbFacade;
}
public SessionController getSessionController() {
return sessionController;
}
public void setSessionController(SessionController sessionController) {
this.sessionController = sessionController;
}
public Institution getCurrent() {
if (current == null) {
current = new Institution();
current.setInstitutionType(InstitutionType.CollectingCentre);
}
return current;
}
public void setCurrent(Institution current) {
this.current = current;
}
public void delete() {
if (current != null) {
current.setRetired(true);
current.setRetiredAt(Calendar.getInstance(TimeZone.getTimeZone("IST")).getTime());
current.setRetirer(sessionController.getLoggedUser());
getFacade().edit(current);
UtilityController.addSuccessMessage("DeleteSuccessfull");
} else {
UtilityController.addSuccessMessage("NothingToDelete");
}
recreateModel();
getItems();
current = null;
getCurrent();
}
private InstitutionFacade getFacade() {
return ejbFacade;
}
public List<Institution> getItems() {
// items = getFacade().findAll("name", true);
String sql = "SELECT i FROM Institution i where i.retired=false and i.institutionType = com.divudi.data.InstitutionType.CollectingCentre order by i.name";
items = getEjbFacade().findBySQL(sql);
if (items == null) {
items = new ArrayList<Institution>();
}
return items;
}
}

java.lang.NullPointerException selectOneMenu convertor

I have a class Specialization
public class Specialization implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "specialization")
private Collection<Doctor> doctorCollection;
In my webpage i have a selectOneMenu
<h:selectOneMenu value="#{specializationMB.specialization}"
converter="#{specializationConverter}">
<f:selectItems value="#{specializationMB.allSpecializations}" var="specialization"
itemLabel="#{specialization.name}" itemValue="#{specialization}" />
</h:selectOneMenu>
GenericDao where is the find method
public abstract class GenericDao<T> {
#PersistenceContext
private EntityManager em;
private Class<T> entityClass;
public GenericDao(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void create(T entity) {
em.persist(entity);
}
public void delete(T entity) {
T toRemoved = em.merge(entity);
em.remove(toRemoved);
}
public T update(T entity) {
return em.merge(entity);
}
public T find(int entityID) {
return em.find(entityClass, entityID);
}
#SuppressWarnings({"unchecked", "rawtypes"})
public List<T> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}
}
I create the converter for my class Specialization
public class SpecializationConverter implements Converter{
private static SpecializationDao sdao = new SpecializationDao();
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
return sdao.find(new Integer(value));
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
return ((Specialization) value).getId().toString();
}
}
But I get an error with my selectOneMenu, when i go to the next page.
java.lang.NullPointerException
at pl.ePrzychodnia.dao.GenericDao.find(GenericDao.java:40)
at pl.ePrzychodnia.converter.SpecializationConverter.getAsObject(SpecializationConverter.java:24)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:202)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:319)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
I don't now why. Can anyone help?
private static SpecializationDao sdao = new SpecializationDao();
Assuming this DAO is a subclass of your GenericDAO, can you tell me when is the EntityManager injected? Let the container create your DAO! Your EntityManager is not injected, therefore you get the NPE.
I would create a stateless session bean (if you work with EJB) and then inject it into the converter.
#Stateless
public class SpecializationService extends GenericCRUDService {...}
public class SpecializationConverter implements Converter{
#Inject
private SpecializationService specializationService;
...
I also think that the term and pattern DAO is a bit outdated. Read about it for example here.

JSF 2: Can't load object in selectOneMenu

I'm trying to fill a dropdown menu, with some objects that I retrieve from database.
So, after reading this topic I did this:
<h:form id="register_form">
<h:panelGrid columns="3">
<h:outputLabel for="client" value="Client:" />
<h:selectOneMenu id="client" value="#{reuniaoc.cliente}" converter="#{clienteConverter}" >
<f:selectItems value="#{reuniaoc.clientes}" var="_cliente" itemValue="#{_cliente}" itemLabel="#{_cliente.id}" />
<f:ajax event="blur" render="m_client" />
</h:selectOneMenu>
<h:message id="m_client" for="client" />
</h:panelGrid>
</h:form>
This is my controller :
package control;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import model.Cliente;
import utility.Message;
import bean.ReuniaoBean;
import eao.ClienteEAO;
import eao.ReuniaoEAO;
#ManagedBean(name="reuniaoc")
#RequestScoped
public class ReuniaoController implements Serializable {
private static final long serialVersionUID = 7737795872305798041L;
#EJB ReuniaoEAO rEAO;
#EJB ClienteEAO cEAO;
private ReuniaoBean rb;
private Cliente cliente;
private List<Cliente> clientes;
#PostConstruct
public void init() {
clientes = cEAO.list();
}
private void addMessage(Message message){
FacesMessage fMessage = new FacesMessage(message.getMessage());
FacesContext.getCurrentInstance().addMessage(null, fMessage);
}
public void register(){
Message message = rEAO.create(rb.getReuniao());
addMessage(message);
}
public String getClientes(){
for (Cliente c : clientes)
System.out.println(c.getFantasia());
return "/funcionario/register/reuniao.xhtml?faces-redirect=true";
}
// get's and set's
public ReuniaoBean getRb() {
return rb;
}
public void setRb(ReuniaoBean rb) {
this.rb = rb;
}
public void setClientes(List<Cliente> clientes) {
this.clientes = clientes;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
}
And my converter:
package bean.converter;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
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;
import javax.faces.convert.ConverterException;
import model.Cliente;
import eao.ClienteEAO;
#ManagedBean
#RequestScoped
public class ClienteConverter implements Converter {
#EJB private ClienteEAO clienteEAO;
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (!(value instanceof Cliente) || ((Cliente) value).getId() == null) {
return null;
}
return String.valueOf(((Cliente) value).getId());
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null || !value.matches("\\d+")) {
return null;
}
Cliente c = clienteEAO.find(Integer.valueOf(value));
if (c == null) {
throw new ConverterException(new FacesMessage("Unknown operation ID: " + value));
}
return c;
}
}
But when I try to load the page, gives me this error: (sorry for the exception be so long)
java.lang.IllegalArgumentException
at com.sun.faces.renderkit.SelectItemsIterator.initializeItems(SelectItemsIterator.java:216)
at com.sun.faces.renderkit.SelectItemsIterator.hasNext(SelectItemsIterator.java:135)
at com.sun.faces.renderkit.html_basic.MenuRenderer.renderOptions(MenuRenderer.java:762)
at com.sun.faces.renderkit.html_basic.MenuRenderer.renderSelect(MenuRenderer.java:844)
at com.sun.faces.renderkit.html_basic.MenuRenderer.encodeEnd(MenuRenderer.java:298)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312)
at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
For me it seems very consistent my code, but there's something I'm missing here.
Any idea ?
public String getClientes(){
for (Cliente c : clientes)
System.out.println(c.getFantasia());
return "/funcionario/register/reuniao.xhtml?faces-redirect=true";
}
This <f:selectItems value> getter doesn't return the list of clients. It returns a navigation case string, which isn't recognized as a valid value argument of <f:selectItems>. It look like that you're mixing action methods with property getters.
Fix the getter accordingly to be a real getter:
public List<Cliente> getClientes() {
return clientes;
}
The setter method on that property is by the way unnecessary. It won't be used in any way in this construct.
See also:
Our h:selectOneMenu wiki page

EJB3 - JSF cannot update entity it excute insert statement why?

hello all new problem i cant solved
i have 1 entity below
package com.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author Kency
*/
#Entity
#Table(name = "about")
#NamedQueries({
#NamedQuery(name = "About.findAll", query = "SELECT a FROM About a"),
#NamedQuery(name = "About.findByAboutTitle", query = "SELECT a FROM About a WHERE a.aboutTitle = :aboutTitle")})
public class About implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "about_title")
private String aboutTitle;
#Basic(optional = false)
#Lob
#Column(name = "content")
private String content;
public About() {
}
/* public About(String aboutTitle) {
this.aboutTitle = aboutTitle;
}*/
public About(String aboutTitle, String content) {
this.aboutTitle = aboutTitle;
this.content = content;
}
public About(String aboutTitle) {
this.aboutTitle = aboutTitle;
}
public String getAboutTitle() {
return aboutTitle;
}
public void setAboutTitle(String aboutTitle) {
this.aboutTitle = aboutTitle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aboutTitle != null ? aboutTitle.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 About)) {
return false;
}
About other = (About) object;
if ((this.aboutTitle == null && other.aboutTitle != null) || (this.aboutTitle != null && !this.aboutTitle.equals(other.aboutTitle))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.About[aboutTitle=" + aboutTitle + "]";
}
}
my stateless bean
package com.DAO;
import com.entity.About;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author Kency
*/
#Stateless
#LocalBean
public class AboutDAO {
#PersistenceContext(unitName = "mcGrawLibPro-ejbPU")
private EntityManager em;
public About retrieveAbout(){
Query query = em.createNamedQuery("About.findAll");
return (About) query.getSingleResult();
}
public void persist(Object object) {
em.persist(object);
}
public About updateAbout(About abouts){
return em.merge(abouts);
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
my JSF managed bean controller
package com.mcgraw.controller;
import com.DAO.AboutDAO;
import com.entity.About;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
/**
*
* #author Kency
*/
#ManagedBean
#SessionScoped
public class AboutController implements Serializable{
#EJB
private AboutDAO aboutDAO;
private About about ;
private String toolbar = "maxi";
public String getToolbar() {
return toolbar;
}
public void setToolbar(String toolbar) {
this.toolbar = toolbar;
}
public About getAbout() {
return aboutDAO.retrieveAbout();
}
public void setAbout(About about) {
this.about = about;
}
/** Creates a new instance of AboutController */
public AboutController() {
about = new About();
}
public void updateAbout(){
about = aboutDAO.updateAbout(about);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"", "Update ok"));
}
}
my JSF page code
<p:dialog widgetVar="about" header="About">
<f:view>
<h:form>
<h:inputText value="#{aboutController.about.aboutTitle}"/>
<p:editor value="#{aboutController.about.content}" widgetVar="editor"/>
<p:commandButton value="Submit" onclick="editor.saveHTML()" action="#{aboutController.updateAbout}"/>
<p:messages/>
</h:form>
</f:view>
</p:dialog>
my problem is when i click submit button it not update it throw exception null in insert statement
i want update but why it insert to database??
everybody have idea for solve it ? thank you
my stacktrace
WARNING: Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'about_title' cannot be null
Error Code: 1048
Call: INSERT INTO about (about_title, content) VALUES (?, ?)
bind => [null, null]
Query: InsertObjectQuery(com.entity.About[aboutTitle=null])
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:801)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:867)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:587)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:530)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeCall(AbstractSession.java:914)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:205)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:191)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:334)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:461)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:286)
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:675)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:589)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:109)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:86)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2857)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1225)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1207)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1167)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:197)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:103)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3260)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1403)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:547)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1508)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3128)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:268)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:412)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:837)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5040)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4805)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2004)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:198)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84)
at $Proxy114.updateAbout(Unknown Source)
at com.DAO.__EJB31_Generated__AboutDAO__Intf____Bean__.updateAbout(Unknown Source)
at com.mcgraw.controller.AboutController.updateAbout(AboutController.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:98)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:775)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1267)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at com.mcgraw.controller.UserLoginFilter.doFilter(UserLoginFilter.java:60)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at com.mcgraw.controller.UserLoginFilter.doFilter(UserLoginFilter.java:60)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:619)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'about_title' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2409)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:792)
... 91 more
column content in database type is TEXT
You've bound your JSF input element to #{aboutController.about}. This invokes the getter:
public About getAbout() {
return aboutDAO.retrieveAbout();
}
Which in turn invokes the DB query:
public About retrieveAbout(){
Query query = em.createNamedQuery("About.findAll");
return (About) query.getSingleResult();
}
So you are getting a new About object every time the getter is invoked. What you should be doing is binding to a specific "about" instance, then sending that instance back to your Stateless Session Bean to be updated. You store this "about" instance as the property of your Managed Bean, and return that with the Managed Bean's getter.

Resources