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).
Related
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>
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.
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.
I have the following form, that I would like to submit only with my p:commandButton, however, I am getting submission in all my input boxes, how do I submit a form on p:commandButton only?
<h:form>
<p:panel header="Lista de Referências" id="panel">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel>Referência</h:outputLabel>
<p:inputText value="#{entradaProdutoController.referencia}"
onkeypress="if (event.keyCode == 13) {onchange(); return false; }">
<f:ajax event="change"
render="textDescri"
listener="#{entradaProdutoController.listener}"/>
</p:inputText>
<h:outputLabel>Descrição</h:outputLabel>
<h:outputText id="textDescri" value="#{entradaProdutoController.replyWith}" />
<h:outputLabel>Quantidade</h:outputLabel>
<p:inputText size="5" value="#{entradaProdutoController.quantidade}" />
</h:panelGrid>
</p:panel>
<p:commandButton value="Adicionar" update="printTable" actionListener="#{entradaProdutoController.addAction(event)}">
</p:commandButton>
I believe that onchange() method is causing the page to be submitted when enter is pressed, if you don't want that behavior try removing...
onkeypress="if (event.keyCode == 13) {onchange(); return false; }"
Tired the above suggestions with no successful results, so as a workaround this is what I am doing, this is probably not a best practice but it works(the hammering way of doing this):
<?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"
>
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h1>Adicionar Referências</h1>
<h:form id="formID" onkeypress="if (event.keyCode == '13') {return false;}">
<h:outputLabel>Referência</h:outputLabel>
<h:inputText id="referenciaLoookup" value="#{testController.referencia}"
onkeypress="if (event.keyCode == '13') {document.getElementById('formID:testeButton').click()}"
>
</h:inputText>
<h:inputText value="#{testController.referencia}"
onkeypress="if (event.keyCode == 13) { onchange(); return false; }">
<f:ajax event="change" listener="#{testController.teste(event)}" />
</h:inputText>
<p:commandButton id="lookup" value="lookup"
actionListener="#{testController.listener(a)}"/>
<p:commandButton id="adicionar" value="Adicionar"
actionListener="#{testController.addAction(e)}">
</p:commandButton>
<p:commandButton id="testeButton" value="teste" style="visibility: hidden;"
actionListener="#{testController.teste(event)}"/>
</h:form>
</h:body>
</html>
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.