I can't get the primeFaces <p:filedownload work. While I succeed in downloading the file using a custom download bean. Seems like the issu is related to the primefaces file download ActionListener but I don't see how. Does anyone have a clue? Thanks.
Here is my bean:
#ManagedBean(name="fileDownloadBean")
#SessionScoped
public class FileDownloadBean implements Serializable {
private StreamedContent file;
public StreamedContent getFile() {
return file;
}
public void setFile(StreamedContent file) {
this.file = file;
}
/** Creates a new instance of FileDownloadBean */
public FileDownloadBean() {
InputStream stream = this.getClass().getResourceAsStream("sessionlog.csv");
file = new DefaultStreamedContent(stream, "application/csv", "sessionlog.csv");
}
}
and here is my view code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:o="http://openfaces.org/"
template="./../template.xhtml">
<ui:define name="title">
#{bundle.Log}
</ui:define>
<ui:define name="body">
<h:form>
<p:separator style="height: 10px;margin-bottom: 10px;margin-top: 0px;"/>
<p:commandButton value="#{bundle.Log}" image="ui-icon ui-icon-link" ajax="false" disabled="false">
<p:fileDownload value="#{fileDownloadBean.file}" />
</p:commandButton>
</ui:composition>
I get a 500 error: NullPointerException :
HTTP Status 500 -
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException
root cause
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1 logs.
GlassFish Server Open Source Edition 3.1
LOG:
WARNING: StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:59)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:769)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
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:409)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
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 com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
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)
InputStream stream = this.getClass().getResourceAsStream("sessionlog.csv");
The way as you have located the CSV file expects it to be in the same package as the current class, the FileDownloadBean.
If it is actually located in the package root, then you should rather be using:
InputStream stream = this.getClass().getResourceAsStream("/sessionlog.csv");
Or if it is actually located in a different package, for example com.example, then you should rather be using:
InputStream stream = this.getClass().getResourceAsStream("/com/example/sessionlog.csv");
Or if it is actually located in the root of the public webcontent (there where the /WEB-INF folder also is, among all other web files), then you should rather be using:
InputStream stream = externalContext.getResourceAsStream("/sessionlog.csv");
(which by the way also works fine for the WAR classes instead of this.getClass())
I am modify my InputStream the code
InputStream stream = this.getClass().getResourceAsStream("sessionlog.csv");
change by
InputStream stream = new FileInputStream(new File("URL"))
it was solution.
Are you sure that you are successfully loading the CSV file as a resource from the Class? It looks like the InputStream may be null.
My fileuplaad.xhtml is as shown below
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:form id="downloadFileForm">
<p:commandButton id="downloadLink" value="Download" ajax="false"
onclick="PrimeFaces.monitorDownload(start, stop)"
icon="ui-icon-arrowthichk-s">
<p:fileDownload value="#{fileDownloadController.file}" />
</p:commandButton>
</h:form>
</html>
Here is my bean:
#ManagedBean(name="fileDownloadController")
public class FileDownloadController implements Serializable {
private static final long serialVersionUID = 1L;
private StreamedContent file;
public FileDownloadController() {
InputStream stream = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream("/download/FileName.csv");
file = new DefaultStreamedContent(stream, "download/csv", "FileName.csv");
}
public StreamedContent getFile() {
return file;
}
}
Related
I'm making a project to school in JSF and I have few problems with that.
First of all, the h:commandButton doesn't work properly when I want to redirect myself to another page of the project by pushing it. There is an error displayed:
javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
index.jsp:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>Firma Komputerowa - Baza Danych</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/table-style.css" />
</head>
<body>
<f:view>
<h:form>
<h:panelGrid columns="3">
<h:commandButton action="#{producentBean.redirect }" value="Dodaj"/>
</h:panelGrid>
<h:panelGrid>
<h:dataTable value="#{producentBean.List}" var="p"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row" border="1" >
<h:column>
<f:facet name="header">ID producenta</f:facet>
<h:inputText value="#{p.getId}"/>
</h:column>
<h:column>
<f:facet name="header">Nazwa producenta</f:facet>
<h:inputText value="#{p.getNazwa}" />
</h:column>
<h:column>
<f:facet name="header">NIP</f:facet>
<h:inputText value="#{p.getNip}" />
</h:column>
<h:column>
<f:facet name="header">REGON</f:facet>
<h:inputText value="#{p.getRegon}" />
</h:column>
<h:column>
<f:facet name="header">Miasto</f:facet>
<h:inputText value="#{p.getMiasto}" />
</h:column>
<h:column>
<f:facet name="header">Adres</f:facet>
<h:inputText value="#{p.getAdres}" />
</h:column>
<h:column>
<f:facet name="header">Telefon</f:facet>
<h:inputText value="#{p.getTel}" />
</h:column>
<h:column>
<f:facet name="header">E-mail</f:facet>
<h:inputText value="#{p.getEmail}" />
</h:column>
</h:dataTable>
</h:panelGrid>
</h:form>
</f:view>
...
</body>
</html>
ProducentBean.java:
public class ProducentBean extends Polacz implements Serializable {
public String redirect() {
return "dodaj_pr";
}
}
I was trying to do it in many ways, but I can't deal with it.
I also have an another question: is there in JSF a possibility to display a table dynamically from database, for example by choosing a table name selecting an option in ? My database contains three tables with different count of colums each.
I'll be very happy if somebody gives me some advices.
EDIT:
OK, I tried to do this:
private String dodajPrUrl = "dodaj_pr?faces-redirect=true";
public String getDodajPrUrl() {
return this.dodajPrUrl;
}
public void setDodajPrUrl(String newUrl) {
this.dodajPrUrl = newUrl;
}
and in index.jsp:
<h:commandButton action="#{producentBean.redirect }" value="Dodaj" />
It gives me still the same error.
EDIT2:
Stack trace:
SEVERE: javax.faces.FacesException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
javax.faces.FacesException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at com.sun.faces.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:142)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
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)
Caused by: javax.faces.component.UpdateModelException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at javax.faces.component.UIInput.updateModel(UIInput.java:853)
at javax.faces.component.UIInput.processUpdates(UIInput.java:735)
at javax.faces.component.UIData.iterate(UIData.java:2001)
at javax.faces.component.UIData.processUpdates(UIData.java:1253)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIForm.processUpdates(UIForm.java:281)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231)
at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
... 26 more
Caused by: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at com.sun.el.parser.AstValue.setValue(AstValue.java:207)
at com.sun.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:291)
at javax.faces.component.UIInput.updateModel(UIInput.java:818)
... 35 more
Look at the stack trace. Here's the most important part:
Caused by: javax.faces.component.UpdateModelException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at javax.faces.component.UIInput.updateModel(UIInput.java:853)
at javax.faces.component.UIInput.processUpdates(UIInput.java:735)
at javax.faces.component.UIData.iterate(UIData.java:2001)
at javax.faces.component.UIData.processUpdates(UIData.java:1253)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIForm.processUpdates(UIForm.java:281)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231)
at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
... 26 more
Read from bottom to top. During update model values phase, JSF is traversing the component tree starting from UIViewRoot component (<f:view>). In an UIForm component (<h:form>) there is an UIData component (<h:dataTable>) which has an UIInput component (<h:inputText>) which needs to be processed. The updateModel() basically needs to put the submitted, converted and validated value in the model (the managed bean). However, that operation has failed because the property is not writable (i.e. the setter method cannot be found based on the EL expression syntax).
Well, let's look at the properties of your <h:inputText> components in general.
<h:inputText value="#{p.getId}"/>
...
<h:inputText value="#{p.getNazwa}" />
...
<h:inputText value="#{p.getNip}" />
Wait, that's strange. They start all with "get"! This is definitely not normal. JSF is then looking for methods like setGetId(), setGetNazwa(), etc which just doesn't make sense (and you likely also don't have, given this exception). It's expected that they represent concrete property names like "id", "nazwa", "nip", etc and not full method names.
Thus, so in the model:
private Long id;
private String nazwa;
private String nip;
// Add/generate getters and setters in the following syntax:
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// ...
And so in the view:
<h:inputText value="#{p.id}"/>
...
<h:inputText value="#{p.nazwa}" />
...
<h:inputText value="#{p.nip}" />
This is however already covered in a bit sane JSF book/tutorial/resource. Are you absolutely positive that you were reading the right one? Your question also shows that you're using JSF 2.0 in combination with the deprecated JSP view technology instead of its successor Facelets. Start at our JSF wiki page.
You have few problems here. First, in your input components you have values like p.getId. In your bean, you probably have methods called getId and setId, but this means that you have property called just id which you can read and write. So change your values to: p.id, p.nazwa, p.nip... You can see that I'm using all lower letters, not Id but id.
Second, you should change your action method to something like this (if you want redirect):
public String redirect() {
return "dodaj_pr?faces-redirect=true";
}
and command button tag to something like this:
<h:commandButton action="#{producentBean.redirect}" value="Dodaj" />
I had the same mistake. The error was that in the value property of the inputext in the EL there were blank spaces between } and " as shown below.
<h:inputText id="txtNroOficio" value="# {bean.nombre} " />
I deleted the blank spaces and it worked.
Don't give the () in your command button. In your bean method return some string and use navigation to move to another page.
This non-working implementation tries to start a new ScheduledExecutorService to dynamically push new Items to the client and update the form:
index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui" xmlns:ui="http://java.sun.com/jsf/facelets"
xml:lang="en" lang="en">
<h:head>
<title>GG Well Trade</title>
</h:head>
<h:body>
<h:form>
<p:socket channel="/notify" onMessage="#{bean.add()}"/>
<p:commandButton value="Start" action="#{bean.start()}"/>
<ui:repeat value="#{bean.items}" var="item" id="content">
<p:outputLabel for="foo" value="#{item.label}" />
<p:inputText id="foo" value="#{item.value}" />
<p:commandButton value="Remove" action="#{bean.remove(item)}" update="#form" />
<br/>
</ui:repeat>
<!--<p:commandButton value="Add" action="#{bean.add}" update="#form" />-->
</h:form>
</h:body>
</html>
Item.class
public class Item {
private String label;
private String value;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Bean.class
#ManagedBean
#ViewScoped
#PushEndpoint("/notify")
public class Bean implements Serializable{
private List<Item> items;
#PostConstruct
public void init() {
items = new ArrayList<Item>();
}
public void start() {
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(()->add(),0,3,TimeUnit.SECONDS);
}
public void add() {
Item item = new Item();
item.setLabel("label" + items.size());
items.add(item);
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/notify", item);
}
#OnMessage(encoders = {JSONEncoder.class})
public Item onMessage(Item item){
return item;
}
public void remove(Item item) {
items.remove(item);
}
public List<Item> getItems() {
return items;
}
}
Pressing the Add button doesn't update the form, Start button instead does but only on clicks. Is there better ways to do this?
EDIT: exception raised:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service(FacesServlet.java:671)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
Bean.add(Bean.java:43)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
javax.el.BeanELResolver.invoke(BeanELResolver.java:158)
javax.el.CompositeELResolver.invoke(CompositeELResolver.java:79)
org.apache.el.parser.AstValue.getValue(AstValue.java:159)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
org.primefaces.component.socket.Socket.getOnMessage(Socket.java:125)
org.primefaces.component.socket.SocketRenderer.encodeEnd(SocketRenderer.java:55)
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.5.8 logs.
This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 6 years ago.
I write simple code but it don't work!
Here are index.xhtml file
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Проверка</title>
</h:head>
<h:body>
<h:form>
<h:inputText id="text" value="#{testBean.testString}"/>
<h:commandButton id="button" action="#{testBean.buttonClick()}" value="сохранить в БД"/>
</h:form>
</h:body>
</html>
Here are nextpage.xhtml file
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:outputText value="#{testBean.allTestItem}"/>
</h:body>
</html>
Here are TestBean.java file
#Stateful
#Named(value = "testBean")
#SessionScoped
public class TestBean implements Serializable {
#Inject
EntityManager em;
String testString = "test0";
public TestBean() {
}
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
public String allTestItem() {
String jpql = "SELECT te FROM " + TestEntity.class.getName() + " te";
Query query = em.createQuery(jpql);
return query.getResultList().toString();
}
public String buttonClick() {
TestEntity te = new TestEntity();
te.setTest(testString);
em.persist(te);
return "nextpage";
}
}
Here are EntityManagerAdapter.java file
#Stateful
#Named(value = "testBean")
#SessionScoped
public class TestBean implements Serializable {
#Inject
EntityManager em;
String testString = "test0";
public TestBean() {
}
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
public String allTestItem() {
String jpql = "SELECT te FROM " + TestEntity.class.getName() + " te";
Query query = em.createQuery(jpql);
return query.getResultList().toString();
}
public String buttonClick() {
TestEntity te = new TestEntity();
te.setTest(testString);
em.persist(te);
return "nextpage";
}
}
Exception I get
javax.el.PropertyNotFoundException: /index.xhtml #10,68 value="#{testBean.testString}": Target Unreachable, identifier 'testBean' resolved to null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
at javax.faces.component.UIInput.validate(UIInput.java:976)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'testBean' resolved to null
at com.sun.el.parser.AstValue.getTarget(AstValue.java:174)
at com.sun.el.parser.AstValue.getType(AstValue.java:86)
at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
... 40 more
Explain me please what's the problem?
It means that CDI couldn't create an instance of TestBean class to satisfy the request. After reviewing your design, it is pretty unclear what you're trying to do. Usually, a CDI bean should not be an EJB. Remove the EJB #Stateful annotation from TestBean and it should work as expected.
I'm making a project to school in JSF and I have few problems with that.
First of all, the h:commandButton doesn't work properly when I want to redirect myself to another page of the project by pushing it. There is an error displayed:
javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
index.jsp:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>Firma Komputerowa - Baza Danych</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/table-style.css" />
</head>
<body>
<f:view>
<h:form>
<h:panelGrid columns="3">
<h:commandButton action="#{producentBean.redirect }" value="Dodaj"/>
</h:panelGrid>
<h:panelGrid>
<h:dataTable value="#{producentBean.List}" var="p"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row" border="1" >
<h:column>
<f:facet name="header">ID producenta</f:facet>
<h:inputText value="#{p.getId}"/>
</h:column>
<h:column>
<f:facet name="header">Nazwa producenta</f:facet>
<h:inputText value="#{p.getNazwa}" />
</h:column>
<h:column>
<f:facet name="header">NIP</f:facet>
<h:inputText value="#{p.getNip}" />
</h:column>
<h:column>
<f:facet name="header">REGON</f:facet>
<h:inputText value="#{p.getRegon}" />
</h:column>
<h:column>
<f:facet name="header">Miasto</f:facet>
<h:inputText value="#{p.getMiasto}" />
</h:column>
<h:column>
<f:facet name="header">Adres</f:facet>
<h:inputText value="#{p.getAdres}" />
</h:column>
<h:column>
<f:facet name="header">Telefon</f:facet>
<h:inputText value="#{p.getTel}" />
</h:column>
<h:column>
<f:facet name="header">E-mail</f:facet>
<h:inputText value="#{p.getEmail}" />
</h:column>
</h:dataTable>
</h:panelGrid>
</h:form>
</f:view>
...
</body>
</html>
ProducentBean.java:
public class ProducentBean extends Polacz implements Serializable {
public String redirect() {
return "dodaj_pr";
}
}
I was trying to do it in many ways, but I can't deal with it.
I also have an another question: is there in JSF a possibility to display a table dynamically from database, for example by choosing a table name selecting an option in ? My database contains three tables with different count of colums each.
I'll be very happy if somebody gives me some advices.
EDIT:
OK, I tried to do this:
private String dodajPrUrl = "dodaj_pr?faces-redirect=true";
public String getDodajPrUrl() {
return this.dodajPrUrl;
}
public void setDodajPrUrl(String newUrl) {
this.dodajPrUrl = newUrl;
}
and in index.jsp:
<h:commandButton action="#{producentBean.redirect }" value="Dodaj" />
It gives me still the same error.
EDIT2:
Stack trace:
SEVERE: javax.faces.FacesException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
javax.faces.FacesException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at com.sun.faces.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:142)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
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)
Caused by: javax.faces.component.UpdateModelException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at javax.faces.component.UIInput.updateModel(UIInput.java:853)
at javax.faces.component.UIInput.processUpdates(UIInput.java:735)
at javax.faces.component.UIData.iterate(UIData.java:2001)
at javax.faces.component.UIData.processUpdates(UIData.java:1253)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIForm.processUpdates(UIForm.java:281)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231)
at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
... 26 more
Caused by: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at com.sun.el.parser.AstValue.setValue(AstValue.java:207)
at com.sun.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:291)
at javax.faces.component.UIInput.updateModel(UIInput.java:818)
... 35 more
Look at the stack trace. Here's the most important part:
Caused by: javax.faces.component.UpdateModelException: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at javax.faces.component.UIInput.updateModel(UIInput.java:853)
at javax.faces.component.UIInput.processUpdates(UIInput.java:735)
at javax.faces.component.UIData.iterate(UIData.java:2001)
at javax.faces.component.UIData.processUpdates(UIData.java:1253)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIForm.processUpdates(UIForm.java:281)
at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1242)
at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1231)
at com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:78)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
... 26 more
Read from bottom to top. During update model values phase, JSF is traversing the component tree starting from UIViewRoot component (<f:view>). In an UIForm component (<h:form>) there is an UIData component (<h:dataTable>) which has an UIInput component (<h:inputText>) which needs to be processed. The updateModel() basically needs to put the submitted, converted and validated value in the model (the managed bean). However, that operation has failed because the property is not writable (i.e. the setter method cannot be found based on the EL expression syntax).
Well, let's look at the properties of your <h:inputText> components in general.
<h:inputText value="#{p.getId}"/>
...
<h:inputText value="#{p.getNazwa}" />
...
<h:inputText value="#{p.getNip}" />
Wait, that's strange. They start all with "get"! This is definitely not normal. JSF is then looking for methods like setGetId(), setGetNazwa(), etc which just doesn't make sense (and you likely also don't have, given this exception). It's expected that they represent concrete property names like "id", "nazwa", "nip", etc and not full method names.
Thus, so in the model:
private Long id;
private String nazwa;
private String nip;
// Add/generate getters and setters in the following syntax:
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// ...
And so in the view:
<h:inputText value="#{p.id}"/>
...
<h:inputText value="#{p.nazwa}" />
...
<h:inputText value="#{p.nip}" />
This is however already covered in a bit sane JSF book/tutorial/resource. Are you absolutely positive that you were reading the right one? Your question also shows that you're using JSF 2.0 in combination with the deprecated JSP view technology instead of its successor Facelets. Start at our JSF wiki page.
You have few problems here. First, in your input components you have values like p.getId. In your bean, you probably have methods called getId and setId, but this means that you have property called just id which you can read and write. So change your values to: p.id, p.nazwa, p.nip... You can see that I'm using all lower letters, not Id but id.
Second, you should change your action method to something like this (if you want redirect):
public String redirect() {
return "dodaj_pr?faces-redirect=true";
}
and command button tag to something like this:
<h:commandButton action="#{producentBean.redirect}" value="Dodaj" />
I had the same mistake. The error was that in the value property of the inputext in the EL there were blank spaces between } and " as shown below.
<h:inputText id="txtNroOficio" value="# {bean.nombre} " />
I deleted the blank spaces and it worked.
Don't give the () in your command button. In your bean method return some string and use navigation to move to another page.
I am learning RichFaces. Added a4j:commandButton to .xhtml. Below is my .xhtml code,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j">
<h:head>
</h:head>
<h:body>
<h:form>
<rich:panel>
<h:panelGrid column="2">
<h:inputText value="#{echoBean.name}"/>
<h:outputText value="#{echoBean.name}" id="echoTxt" />
<h:outputText value="Count" />
<h:outputText id="countTxt" value="#{echoBean.count}" />
</h:panelGrid>
<a4j:commandButton value="Send" actionListener="#{echoBean.incrementCount}" reRender="echoTxt, countTxt"/>
</rich:panel>
</h:form>
</h:body>
</html>
I am using richfaces 4. So I have not given any a4j filters
But a4j:commandButton is not working. It is not doing any action on click. And no error in stack trace.
Am I missing something?
Thanks
Update:
I have replaced the the actionListener with action.
Now onclick of the button it throws the following exception,
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:165)
at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1560)
at com.sun.faces.application.view.StateManagementStrategyImpl$2.visit(StateManagementStrategyImpl.java:267)
at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1590)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIForm.visitTree(UIForm.java:344)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at com.sun.faces.application.view.StateManagementStrategyImpl.restoreView(StateManagementStrategyImpl.java:254)
at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:188)
at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:123)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:453)
at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:148)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:303)
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:192)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:116)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
my managed Bean code is,
/**
*
*/
package org.droidaceapps.src;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
/**
* #author yasodavenkat
*
*/
#ManagedBean(name="echoBean")
#SessionScoped
public class EchoBean {
private String name;
private int count;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public EchoBean() {
}
public void incrementCount(ActionEvent e){
count = name.length();
}
}
I understand that it is related the state management problem. Is my guess correct? Am I miss anything else?
Thanks
You're using actionListener for your command button, you should use action to make it work.
<a4j:commandButton value="Send" action="#{echoBean.incrementCount}"
reRender="echoTxt, countTxt"/>
Plus, don't forget to set the data you're sending by adding the execute attribute tag. By default, it will submit all the form. You can find more info in the component documentation and you can refer to the online showcase.
UPDATE:
The name variable is null, that's why its throwing that error. That's because you're using. This is because you're doing this
<h:inputText value="#{echoBean.name}"/>
<h:outputText value="#{echoBean.name}" id="echoTxt" />
The echoBean.name is being setted twice in your bean, the first with the inputText value (the text you've entered) and the second time with the outputText value (null). If you want this behavior, you should really look on the showcase link I've added in my post and analyze how it must be done.
These are some steps to solve or check your problem solution. Please note this is not complete solution due to less info about your project (your backing bean not here)
try 'h' or 't' tag and try to run it
check your manage bean you mention your bean scope put it in sessionscope
If this not work then come with your backing bean and faces-config.xml