Primefaces photoCam component not rendering - java

I am using primefaces photoCam component exactly as explained in
https://www.primefaces.org/showcase/ui/multimedia/photoCam.xhtml . unfortunately, unlike in the showcase my photoCam example, mine does not render. I have tried it on Firefox and Chrome the code is as follows:
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
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:form>
<h:panelGrid columns="3">
<p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photos"/>
<p:commandButton type="button" value="Capture" onclick="pc.capture()"/>
<p:imageSwitch effect="zoom" id="photos">
<ui:repeat value="#{photoCamBean.photos}" var="photo">
<p:graphicImage value="/photocam/#{photo}.png" />
</ui:repeat>
</p:imageSwitch>
</h:panelGrid>
</h:form>
</ui:composition>
And the bean
#ManagedBean
#ViewScoped
public class PhotoCamBean {
private List<String> photos = new ArrayList<String>();
private String getRandomImageName() {
int i = (int) (Math.random() * 10000000);
return String.valueOf(i);
}
public List<String> getPhotos() {
return photos;
}
public void oncapture(CaptureEvent captureEvent) {
String photo = getRandomImageName();
this.photos.add(0,photo);
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
}
catch(Exception e) {
throw new FacesException("Error in writing captured image.");
}
}
}
The primefaces showcase photoCam renders a canvas with an adobe flash confirmation window but mine doesn't, what am i missing here?

Adding the meta tag in the head section of the page solves the problem as shown:
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:form>
<h:panelGrid columns="3">
<p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photos"/>
<p:commandButton type="button" value="Capture" onclick="pc.capture()"/>
<p:imageSwitch effect="zoom" id="photos">
<ui:repeat value="#{photoCamBean.photos}" var="photo">
<p:graphicImage value="/photocam/#{photo}.png" />
</ui:repeat>
</p:imageSwitch>
</h:panelGrid>
</h:form>
</ui:composition>
I was able to view the canvas with an adobe flash confirmation window simply by adding the meta tag. Thank you all for your contribution.

Related

Message: Missing PDF in PrimeFaces Extnsions DocumentViewer

I have problem to display StreamedContent PDF in DocumentViewer from Primefaces Extensions (6.2.9) with PrimeFaces 6.2 and MyFaces 2.2.12. I read the same question, but it's an other situation.
Message: Missing PDF in PrimeFaces Extensions DocumentViewer
This is my xhtml code
<p:commandButton icon="fa fa-print" actionListener="#{bean.onPrerender}" />
Dialog code
<p:dialog id="dvDialog" widgetVar="dv_dialog" dynamic="true" header="Document" width="1200px" height="700px" modal="true">
<pe:documentViewer cache="true" height="500" value="#{bean.content}" download="report.pdf" />
</p:dialog>
This is my java code
private StreamedContent content;
public void onPrerender(ActionEvent actionEvent) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, out);
document.open();
for (int i = 0; i < 50; i++) {
document.add(
new Paragraph("All work and no play makes Jack a dull boy"));
}
document.close();
// content = new DefaultStreamedContent(
// new ByteArrayInputStream(out.toByteArray()), "application/pdf");
content = new ByteArrayContent(out.toByteArray(), "application/pdf");
} catch (Exception e) {
e.printStackTrace();
}
PrimeFaces.current().executeScript("PF('dv_dialog').show()");
}
public StreamedContent getContent() {
return content;
}
public void setContent(StreamedContent content) {
this.content = content;
}
The error message
PDF.js v1.10.88 (build: c62a1938)
Message: Missing PDF "http://localhost:8080/hoft/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&pfdrid=1a55ef4c9448951fae5f493579cf80e1&pfdrt=sc&pfdrid_c=true&download=report.pdf".
have anyone clue, what is wrong with my code? it is actually the code in demo showcase Primeface-Extensions with modification.
My project use iframe and the documentviewer will display in a popup dialog. I also tried with #SessionScoped and #ViewScoped, but have no luck.
If I try it in stand alone project, it works (without iframe). May be someone can give clues, how to debug to find the problem.
Please help.... Thank you.
I get error message
pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17581 GET http://localhost:8081/hoft/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&pfdrid=3c954d24c76c30714a581092c23e1489&pfdrt=sc&pfdrid_c=true&download=report.pdf 404
PDFFetchStreamReader # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17581
getFullReader # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:17527
(anonymous) # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:4388
(anonymous) # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1002
resolveCall # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1001
_createStreamSink # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1266
MessageHandler._onComObjOnMessage # pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:1094
pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:19633 Uncaught (in promise) Error: Missing PDF file.
at pdf.viewer.js.xhtml?ln=primefaces-extensions&v=6.2.9:19633
I tried this using:
Java EE 7
GlassFish 4.1.2
PrimeFaces 6.2
PrimeFaces-Extensions 6.2.9
At the bean (class) code:
#ManagedBean
#ApplicationScoped
public class DocumentViewerController {
The scope is #ApplicationScoped. I have a private StreamedContent attribute. And two main public methods:
First method: It's called from actionListener attribute of a p:commandButton. The method receive a parameter (in my case).
public void onPrerender(Tramite tramite) {
tramiteSelected = tramite;
numeroTramite = tramite.getNumero();
contrato = tramite.getContrato();
}
Second method: It's used from a pe:documentViewer inside a dialog component, like this:
<pe:documentViewer id="certificadoViewer"
height="500px"
width="750px"
cache="false"
value="#{documentViewerController.certificado}"
download="certificado_#{documentViewerController.numero}_#{documentViewerController.contrato}.pdf" />
Note: The 2nd method works like a property (getter and setter). THAT'S THE TRICK.
The final code from my project is:
# Bean (DocumentViewerController.java):
package com.epmrpsd.certificado.consulta.controladores;
import com.epmrpsd.certificado.consulta.controladores.util.JsfUtil;
import com.epmrpsd.certificado.consulta.entidades.Tramite;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
/**
*
* #author pbonilla
*/
#ManagedBean
#ApplicationScoped
public class DocumentViewerController {
private StreamedContent content;
private Integer numeroTramite;
private Integer contrato;
private Tramite tramiteSelected;
// Path where the file exists
private String pdfPathDirectory = "C:\\Users\\<user>\\certificados\\";
public void onPrerender(Tramite tramite) {
tramiteSelected = tramite;
numeroTramite = tramite.getNumero();
contrato = tramite.getContrato();
}
public StreamedContent getCertificado() {
InputStream stream = null;
try {
File file = new File(pdfPathDirectory + numeroTramite + "_" + contrato + ".pdf");
if (file.exists()) {
stream = new FileInputStream(file);
} else {
JsfUtil.addErrorMessage("Error", "No se ha encontrado el archivo");
}
this.content = new DefaultStreamedContent(stream, "application/pdf");
} catch (FileNotFoundException fnfex) {
JsfUtil.addErrorMessage("Error", "No se ha encontrado el archivo. Error: " + fnfex.getMessage());
fnfex.printStackTrace();
} catch (Exception e) {
JsfUtil.addErrorMessage("Error", "Se ha generado un error al cargar el certificado. Error: " + e.getMessage());
e.printStackTrace();
}
return content;
}
public void setCertificado(StreamedContent contenido) {
content = contenido;
}
public Tramite getTramiteSelected() {
return tramiteSelected;
}
public void setTramiteSelected(Tramite tramiteSelected) {
this.tramiteSelected = tramiteSelected;
}
public Integer getNumero() {
return numeroTramite;
}
public void setNumero(Integer numeroTramite) {
this.numeroTramite = numeroTramite;
}
public Integer getContrato() {
return contrato;
}
public void setContrato(Integer contrato) {
this.contrato = contrato;
}
}
# View (index.xhtml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pe="http://primefaces.org/ui/extensions">
<h:head>
<title>Consulta de Certificados Digitales</title>
<h:outputStylesheet library="css" name="epmrpsd.css" />
<h:outputStylesheet library="webjars" name="font-awesome/5.5.0/css/all-jsf.css" />
<h:outputStylesheet library="css" name="jsfcrud.css"/>
<h:outputScript library="js" name="jsfcrud.js"/>
<link rel="shortcut icon" type="image/png" href="#{resource['images/logo.png']}"/>
</h:head>
<h:body>
<div id="background" style="position: fixed;">
<h:form id="formCertificados">
<div class="ui-g" style="margin-top: 25px;">
<div class="ui-g-1"></div>
<div class="ui-g-10">
<p:growl id="mensajes" />
<Extra code> ...
<p:outputPanel id="pnlCertificado">
<p:dataTable id="tramitesTable"
value="#{tramiteController.items}"
var="tramite"
rowKey="#{tramite.id}"
selectionMode="single"
selection="#{tramiteController.selected}"
emptyMessage="No se encontraron trámites con los criterios dados"
rows="10"
rowsPerPageTemplate="10,20,30,40,50">
<p:column headerText="Número Trámite" >
<h:outputText value="#{tramite.numero}" />
</p:column>
<p:column headerText="Descripción" >
<h:outputText value="#{tramite.tipo.descripcion}" />
</p:column>
<p:column headerText="Número Contrato" >
<h:outputText value="#{tramite.contrato}" />
</p:column>
<p:column style="text-align: center" headerText="Acción" >
<center>
<p:commandButton id="viewCertificado"
styleClass="ui-priority-primary"
value="Ver certificado"
actionListener="#{documentViewerController.onPrerender(tramite)}"
update=":ViewCertificadoForm"
oncomplete="PF('ViewCertificadoDialog').show()" />
</center>
</p:column>
</p:dataTable>
</p:outputPanel>
</div>
<div class="ui-g-1"></div>
</div>
</h:form>
<ui:include src="ViewCertificado.xhtml"/>
</div>
</h:body>
</html>
And the final component for the view is (ViewCertificado.xhtml):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions">
<ui:composition>
<p:dialog id="ViewCertificadoDlg"
widgetVar="ViewCertificadoDialog"
modal="true"
resizable="false"
appendTo="#(body)"
header="Certificado #{documentViewerController.contrato}">
<h:form id="ViewCertificadoForm">
<h:panelGroup id="display">
<p:panelGrid columns="1" rendered="#{documentViewerController.tramiteSelected != null}">
<pe:documentViewer id="certificadoViewer"
height="500px"
width="750px"
cache="false"
value="#{documentViewerController.certificado}"
download="certificado_#{documentViewerController.numero}_#{documentViewerController.contrato}.pdf" />
</p:panelGrid>
<p:commandButton value="Cerrar" onclick="ViewCertificadoDialog.hide()"/>
</h:panelGroup>
</h:form>
</p:dialog>
</ui:composition>
</html>

PrimeFaces 6.2 issue with CDI Conversations

I updated the PrimeFaces version to 6.2. Everything went good, except for an issue with CDI conversations management.
After the update, it seems like the conversation is initialized at the first access to a page, but it is lost just before the first call to the controller. In fact, when accessing to a page a new conversation is been initialized (and this is correct). But after the first call to a controller method a new conversation is initialized, losing the previous one and all its parameter values. The following calls maintain the last conversation as usual.
With PrimeFaces 6.1 (and previous) this never happened.
Is this a bug or a lack of mine?
After the access to the page, the text displayed is "Init value with conversation id = 1".
By clicking the button, the displayed text changes to "Value set with conversation id = 2".
The following clicks mantain the cid = 2.
Controller
#Named
#ConversationScoped
#LoggedIn
public class TestController implements Serializable {
static final long serialVersionUID = 69823746898775L;
#Inject protected Conversation conversation;
#Inject protected FacesContext facesContext;
rivate String outputValue;
#PostConstruct
public void init() throws IOException {
if (conversation.isTransient()) {
conversation.begin();
conversation.setTimeout(1800000);
}
outputValue = "Init value with conversation id = " + conversation.getId();
}
public void handleCall() {
outputValue = "Value set with conversation id = " + conversation.getId();
}
public String getOutputValue() {
return outputValue;
}
public void setOutputValue(String outputValue) {
this.outputValue = outputValue;
}
}
JSF page
<?xml version="1.0" encoding="UTF-8"?>
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui" contentType="text/html">
<html>
<h:head>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" type='image/x-icon' href='favicon.ico'/>
<ui:insert name="head" />
</h:head>
<h:body onload="javascript: if ('#{param.sessionExpired}'.length != 0) PF('loginDialog').show()">
<h:form id="testForm">
<p:commandButton action="#{testController.handleCall()}" value="Make a call" update="#form" />
<h:outputText value="#{testController.outputValue}" />
</h:form>
</h:body>
</html>
</f:view>

JSF Error Message and Info Message is not working from backing bean

I need a bit help here while setting messages to faces context from a backing bean ,
My page design layout is as follows.Also its using a common layout for all the pages.
ContactUs.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:body>
<ui:composition template="#{language.layout}"> //CommonLayout.xhtml //common template
<ui:define name="content">
<div class="input-cont">
<h:form styleClass="login-form">
<h:messages errorClass="error medium" layout="table" />
<p:inputText value="#{customerBean.contactUsDTO.email}"
id="useremail" name="useremail" type="email"
styleClass="input-text" placeholder="Email" />
<p:inputTextarea value="#{customerBean.contactUsDTO.comments}"
name="txtFeedback" id="txtFeedback"
styleClass="input-text comment-area" placeholder="Comments"</p:inputTextarea>
<div class="btn-cont labels-to-inputs">
<h:commandLink action="#{customerBean.contactUs}"
styleClass="next-btn login-btn ord-btn">Submit</h:commandLink>
</div>
</h:form>
CommonLayout.xhtml Is as follows
<?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://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
>
<f:view locale="#{language.locale}">
<h:head>
<h:body>
<div class="container">
<ui:insert name="leftNav"> <!-- Left Navigation -->
<ui:include src="commonLeft.xhtml" />
</ui:insert>
<div id="content"> <!-- External Page Contents Starts -->
<ui:insert name="content">
</ui:insert>
</div> <!-- External Page Contents Ends -->
</div>
</h:body>
</f:view>
</html>
And ContactBean.java
This bean is session scoped under facesconfig.xml file
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
public class ContactBean{
public String contactUs() {
String response="success" //Testing purpose
if(!response.equalsIgnoreCase("success")){
{raiseError("Service is temporarily unavailable, Try again later");
}
System.out.println("Response from email is "+response);
}
else if(response.equalsIgnoreCase("success")){
System.out.println("Response from email is "+response);
{raiseInfo("Thanks for gettting in touch with Us, We will contact you soon");
}
}
}
return "ContactUs";
}
public void raiseError(String msgText){
FacesContext fc = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msgText, msgText);
fc.addMessage(null, msg);
}//raiseError
public void raiseInfo(String infoMsg){
FacesContext fc = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, infoMsg, infoMsg);
fc.addMessage(null, msg);
}//raiseError
}
This raiseInfo and rasieError messages are not showing any messages to that contact-form page, after adding those as a new message object into faces context also , Its not showing up. What could be the possibly error happening.
As correctly pointed out by #ArgaPK, you have missed to terminate first string parameter and start the second string parameter in the below call of raiseError inside contactUs method, instead of 2 parameters it is one String and hence the error:
raiseError("Service is temporarily unavailable, Try again later");
It should have been a compile time error.
Find the solution:
you have to add <p:growl> tag in your xhtml form.
<h:form styleClass="login-form">
<p:growl id="growl" life="2000" />
....
<h:commandLink action="#{customerBean.contactUs}"
styleClass="next-btn login-btn ord-btn">Submit</h:commandLink>
</h:form>

Gmap primefaces not rendering

I am making a search by id and in my home page I have an inputText and a commandButton. When I click the commandButton, it has to set the id with the number passed in the inputText and redirect me to the map page to track coordinates referring to this id. As I have to access the ManagedBean to set the Id variable, I have to redirect to the map page through a method which returns a String with the "outcome" of the page address. The problem is that the map is not rendering when the page is loaded. If the map page is accessed normally, without the outcome coming from the bean, the map loads correctly, then its not API key problem or wrong coordinates. Does anyone know what is happening or know any other solution?
Home page:
<ui:composition template="/WEB-INF/template/LayoutPadrao.xhtml"
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">
<ui:define name="titulo">Dashboard</ui:define>
<ui:define name="corpo">
<h:form>
<p:panel
style="margin-top:0px;margin-left:450px;width:480px;border: none !important;">
<p:panelGrid id="grid2" columns="2" styleClass="semBorda">
<p:inputText id="pesquisarGado" size="50" style="height:25px;"
value="#{gadoBean.gadoBeanM.name}" required="true"
requiredMessage="Digite o código do gado" />
<p:commandButton action="#{gadoBean.outcome()}"/>
<p:button outcome="gado/rastrearGado"/>
<p:message for="pesquisarGado" display="icon" />
</p:panelGrid>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
ManagedBean:
#Named
#SessionScoped
//attributes and other methods
public String outcome() {
return "gado/rastrearGado";
}
public void inicializar() {
GravarPosicao();//method to record coo in the DB
obterPosicaoPeloId();
}
public void obterPosicaoPeloId() {
mapa = new DefaultMapModel();
tagsCadastradas = new ArrayList<Tag>();
tagsCadastradas = tagsRep.listarTag();
this.getTagsCadastradas().size();
posicoes = new ArrayList<Coordenadas>();
ultimasPosicoes = new ArrayList<Coordenadas>();
String id = this.getGadoBeanM().getName();
cooPorId = coordenadasRep.listarCoords(Long.parseLong(id));
System.out.println("posicoes: " + cooPorId.getPosData());
System.out.println("id: " + id);
coord = new LatLng(cooPorId.getPosLatitude(), cooPorId.getPosLongitude());
mapa.addOverlay(new Marker(coord, "Gado"));
lastLong = (float) cooPorId.getPosLongitude();
lastLat = (float) cooPorId.getPosLatitude();
center = lastLat + "," + lastLong;
System.out.println(center);
}
Map page:
<?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://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f ="http://java.sun.com/jsf/core" xmlns:o="http://omnifaces.org/ui">
<h:head>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeF32jO4j5mAORJTcNICT3o8Nz8G0QZIg"
type="text/javascript"></script>
</h:head>
<title>Rastreamento</title>
<f:metadata>
<f:event listener="#{gadoBean.inicializar}" type="preRenderView" update="#form"/>
</f:metadata>
<h:body>
<h:form>
<p:panel id="panelMap" style="margin-top:100px;margin-left:410px;width:508px;">
<p:gmap id="mapa"
center="#{gadoBean.center}"
zoom="9"
model="#{gadoBean.mapa}"
type="HYBRID"
style="width:600px;height:400px"/>
</p:panel>
</h:form>
</h:body>
</html>
When you use commandButton to navigate, you have to use h:commandButton (JSF) not p:commandButton (primefaces).

p:commandButton does not invoke action after another action invoked

I have simplified everything to just two files as below:
<?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:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui" xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="#{facesContext.externalContext.requestContextPath}/resources/css/default.css" rel="stylesheet" type="text/css" />
<link href="#{facesContext.externalContext.requestContextPath}/resources/css/cssLayout.css" rel="stylesheet" type="text/css" />
<title>Secure</title>
</h:head>
<h:body>
<h:form id="form1">
<p:inputText id="crit" value="#{publisherBean.crit}"/>
<p:commandButton process="#form" update="data" icon="ui-icon-search" action="#{publisherBean.search()}"/>
<p:dataTable id="data" value="#{publisherBean.foundPublishers}" var="pub">
<p:column>
<h:outputText value="#{pub}"/>
</p:column>
</p:dataTable>
</h:form>
<h:form id="form2">
<p:commandButton action="#{publisherBean.save()}" value="Save" update=":form1 #form" />
<h:commandButton action="#{publisherBean.save()}" value="Save">
<f:ajax execute="#form" render=":form1 #form"/>
</h:commandButton>
</h:form>
</h:body>
</html>
And the backing bean:
#ManagedBean
#ViewScoped
public class PublisherBean {
private ArrayList<String> foundPublishers;
private String crit;
private String publisher;
public PublisherBean() {
foundPublishers = new ArrayList<>();
}
public void save() {
crit = "";
foundPublishers.clear();
}
public void search() {
foundPublishers.clear();
foundPublishers.add("Dummy 1");
}
/* Getters and Setters */
}
The problem is: after I pressed the second p:commandButton (Save), the first p:commandButton (search) does not invoke the bean method (traced by tomcat log output).
I traced the XMLHttpRequest and found that in the failed requests, the request header lacks javax.faces.ViewState:-3177489149850736864:913391262441057407. The ajax response is normal - rendering the p:dataTable, only with no results.
Pressing the h:commandButton works. I am not sure whether it is a Primefaces bug or there is something that I missed. I prefer sticking to Primefaces buttons to maintain the same look and feel throughout my app.

Categories

Resources