p:commandButton does not invoke action after another action invoked - java

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.

Related

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).

ConversationScoped bean action not fired using a rendered commandlink

I'm having trouble understanding why a action method on my ConversationScope'd bean doesnt fire. The bean is:
package org.work;
import java.io.Serializable;
import javax.enterprise.context.ConversationScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Named;
#Named
#ConversationScoped
public class NewClass implements Serializable {
private static final long serialVersionUID = 6470665657635110586L;
private boolean b1;
public boolean isB1() {
return b1;
}
public void setB1(boolean b1) {
this.b1 = b1;
}
public void preRenderView(ComponentSystemEvent evt) {
}
public String peformAction() {
return null;
}
}
and my XHTML is:
<?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:f="http://java.sun.com/jsf/core">
<f:view>
<h:head>
</h:head>
<f:metadata>
<f:viewParam name="b1"
value="#{newClass.b1}" />
<f:event type="preRenderView"
listener="#{newClass.preRenderView}"/>
</f:metadata>
<h:body>
<h:form>
<h:commandLink action="#{newClass.setB1(!newClass.b1)}"
style="background-color: #{newClass.b1 ? 'darkorchid' : 'aquamarine'};"
value="btn3"/>
<h:panelGrid rendered="#{newClass.b1}"
columns="1">
<h:commandLink value="edit"
action="#{newClass.peformAction()}" />
</h:panelGrid>
</h:form>
</h:body>
</f:view>
</html>
The performAction() method is not fired after I press the commandLink that should invert the boolean making the other commandLink rendered. When debugging I can see that the boolean is set to true, but it seems to me the "rendered" attribute is evaluated before the viewparams is set. Is this true?
The example works fine with #ManagedBean and #javax.faces.bean.ViewScoped.
I think that you don't have long-running conversation. You could read more information on this site: http://docs.oracle.com/javaee/6/api/javax/enterprise/context/ConversationScoped.html
If you have transient conversation this bean is recreated after every request

Primefaces photoCam component not rendering

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.

CommandButton inside dynamically rendered panelGroup fails to execute actionlistener

I have a very simple xhtml file where a panelGroup containing a commandButton is added to the page on clicking toggle button but this dynamically added commandButton fails to execute its actionlistener on being clicked.
Complete code 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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:panelGroup id="checkDyna">
<h:panelGroup rendered="#{listRetriever.booleanStatus}" >
<h:form>
<p:commandButton value="check" process="#all" actionListener="#{listRetriever.xx()}"/>
</h:form>
</h:panelGroup>
</h:panelGroup>
<h:form>
<p:commandButton value="Toggle" actionListener="#{listRetriever.toggleBooleanStatus()}" update=":checkDyna"/>
</h:form>
</h:body>
</html>
Bean
#ManagedBean(name = "listRetriever")
#RequestScoped
public class ListRetriever implements Serializable {
private boolean booleanStatus;
public void toggleBooleanStatus(){
if (!booleanStatus)
booleanStatus=true;
}
public void xx(){
System.out.println("Invoked***");
}
public boolean isBooleanStatus() {
return booleanStatus;
}
public void setBooleanStatus(boolean booleanStatus) {
this.booleanStatus = booleanStatus;
}
}
On removing rendered="#{listRetriever.booleanStatus}" actionlistener is successfully invoked.
On making the bean ViewScoped too the problem is eliminated but I dont want to make it wider than RequestScoped.
I had this p:commandButton within a conditionally rendered panel whose conditional expression for rendering was evaluating to false while I was trying to execute the actionlistener. This was the cause of actionlistener not getting executed.

Categories

Resources