I am trying to display a random number on a panel through PrimeFaces panel. I have the following xhtml code:
<h:form>
<p:growl id="msgs" showDetail="true" />
<p:panel id="basic" header="Random Number" style="margin-bottom:20px">
<h:panelGrid columns="2" cellpadding="10">
<h:outputText value="#{randomnum.number}" />
</h:panelGrid>
</p:panel>
</h:form>
This panel calls randomnum.number which is like this
import java.io.Serializable;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class randomnum implements Serializable {
private int number;
public randomnum() {
}
public int getNumber() {
return number;
}
#PostConstruct
public void init() {
Random r = new Random();
int Low = 10;
int High = 100;
number = r.nextInt(High-Low) + Low;
System.out.println("Random Number :"+number);
}
}
But when I run my xhtml code, I see the panel but I do not see anything inside it. Also, the System.out.println() output is not displayed on console. How do I resolve the issue? My basic aim is that when I run the xhtml code then a random number must be shown on the panel.
The solution is to use a Class named correct according to the Java Code Conventions: http://www.oracle.com/technetwork/java/codeconventions-135099.html
tl;dr:
Rename your Class "randomnum" to "Randomnum".
This way JSF will find the Bean, instantiate it, call #PostConstruct and display the value.
Related
I have created a session bean but it seems my <h:selectOneMenu> is not storing the value in the bean. Can someone tell me what I am doing wrong?
In the xhtml navigates to another xhtml that displays the results. I do not have any values in faces-config.xml other than the navigation rules since I think managed bean / session bean annotations can replace that
xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<!-- Using a custom header -->
<ui:include src="/resources/ADTHeader.xhtml" />
<h:body>
<h1>Test</h1>
<h:form>
<h:selectOneMenu id="mypick"
value="#{gridMaster_backing.pickedGrid}"
converter="#{categoryConverter}"
title="ADTF" >
<f:selectItems value="#{gridMaster_backing.gridList}" var="prog" itemValue="#{prog.gridid}" itemLabel="#{prog.gridid} - #{prog.program} - #{prog.project} - #{prog.ci}" />
</h:selectOneMenu>
<br /><br />
<h:button value="View Grid" outcome="result" />
</h:form>
</h:body>
</html>
Session bean:
package edu.adtf.web;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.ejb.EJB;
import com.ray.adtf.ejb.*;
import com.ray.adtf.jpa.Gridmaster;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
#ManagedBean
#SessionScoped
public class gridMaster_backing {
#EJB
private GridMasterBean ejb;
private Collection<Gridmaster> mgrid;
private List gridList = new ArrayList();
// pickedGrid holds value picked from the gridid drop down list
private Long pickedGrid;
public Long getPickedGrid() {
//System.out.println("getPicked Grid");
return pickedGrid;
//return (long) 100;
}
public void setPickedGrid(Long pickedGrid) {
this.pickedGrid = pickedGrid;
}
// returns data to show grid form
public Collection<Gridmaster> getGridmaster(Long vgridid){
mgrid = ejb.getAllGrids(vgridid);
return mgrid;
}
public void setGridList(List gridList) {
this.gridList = gridList;
}
// list for grid list drop down
public List getGridList() {
List gridList2 = ejb.getDisplayGridList();
return gridList2;
}
}
converter:
package edu.adtf.web;
import javax.faces.bean.ManagedBean;
import edu.adtf.jpa.Gridmaster;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#ManagedBean(name = "categoryConverterBean")
#FacesConverter(value = "categoryConverter")
public class CategoryConverter implements Converter{
#PersistenceContext
private transient EntityManager em;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
//System.out.println(em.find(Gridmaster.class, new Long(value)));
return em.find(Gridmaster.class, new Long(value));
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
Gridmaster gridmaster;
gridmaster = (Gridmaster) value;
//System.out.println(String.valueOf(gridmaster.getGridid()));
return String.valueOf(gridmaster.getGridid());
}
}
The problem is in the converter you're using. The field of your managed bean from where you're getting/setting the data is of type Long and the default value for <h:selectOneMenu> is of type String, so you only need to use a Long converter. There's a built-in converter for this case: javax.faces.Long. Make sure you're defining that the itemValue for the <h:selectItems> is type Long as well.
The code should look like this:
<h:selectOneMenu id="mypick"
value="#{gridMaster_backing.pickedGrid}"
converter="javax.faces.Long"
title="ADTF">
<!-- #{prog.gridid} must return Long -->
<f:selectItems
value="#{gridMaster_backing.gridList}"
var="prog"
itemValue="#{prog.gridid}"
itemLabel="#{prog.gridid} - #{prog.program} - #{prog.project} - #{prog.ci}" />
</h:selectOneMenu>
This question already has an answer here:
#ViewScoped calls #PostConstruct on every postback request
(1 answer)
Closed 6 years ago.
I've got problem with opening dialog in JSF 2.2.7 and Primefaces 5. I've got button which opens a dialog and the problem is everytime when I click the button #PostConstruct method is executed. Why?
I want to invoke #PostConstruct only 1 time, but I don't want to change to scope to Session (with #SessionScope annotation it works perfectly).
It's my view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:form id="f1">
<p:dialog widgetVar="trainingDialog2" id="d1">
<h:outputText value="#{userViewBean.errorMessage}" />
</p:dialog>
<br />
<p:dataTable id="dt1" value="#{userViewBean.infoList}" var="item">
<p:column>
<p:commandButton id="btn" update=":f1:d1"
oncomplete="PF('trainingDialog2').show()"
styleClass="ui-icon ui-icon-calendar">
<f:setPropertyActionListener value="#{item.id}"
target="#{userViewBean.errorMessage}" />
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
It's my bean:
package pl.jrola.java.www.vigym.viewcontroller.beans.userview;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
#ManagedBean(name = "userViewBean")
#ViewScoped
public class UserViewBean implements Serializable {
private static final long serialVersionUID = 6994205182090669165L;
private String errorMessage;
private List<UserProfileInfoBean> infoList;
public List<UserProfileInfoBean> getInfoList() {
return infoList;
}
public void setInfoList(List<UserProfileInfoBean> infoList) {
this.infoList = infoList;
}
public UserViewBean() {
}
#PostConstruct
public void postConstruct() {
this.infoList = new ArrayList<UserProfileInfoBean>();
for (long i = 0; i < 3; i++) {
this.infoList.add(new UserProfileInfoBean(i));
}
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
You're mixing the annotations for JSF beans and CDI beans, effectively making the bean #RequestScoped, because it's the default for a #ManagedBean.
If you use JSF beans use:
javax.faces.bean.ManagedBean;
javax.faces.bean.ViewScoped;
If you wanna go for CDI beans use:
javax.inject.Named;
javax.faces.view.ViewScoped;
If your server supports CDI you should go for CDI beans.
Read more about the default scopes here:
What is the default Managed Bean Scope in a JSF 2 application?
I have using primefaces in my project. I need to create and delete field dynamically on my project. Here I am going to attached my code please find it
my xhtml page is
<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:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:panelGrid border="0" columns="3" cellpadding="4" columnClasses="control-label">
<h:panelGrid columns="3" cellpadding="4" >
<h:outputText value="Individual Email"/>
<div>
<h:dataTable value="#{utilBean.attachments}" var="attachmentBean" binding="#{utilBean.data}" id="attachments">
<h:column>
<h:inputText id="attachment" value="#{attachmentBean.emailAddress}" binding="#{utilBean.attachment}"/>
</h:column>
<h:column>
<h:commandButton id="delete" value="Delete" immediate="true" actionListener="#{utilBean.deleteAddress}"/>
</h:column>
</h:dataTable>
<h:commandButton id="add" value="Add Email Address" immediate="true" actionListener="#{utilBean.addAddress}" />
</div>
<br/>
</h:panelGrid>
</h:panelGrid>
</ui:composition>
My Bean Is:
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIData;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean
#SessionScoped
public class UtilBean{
private UIData data=null;
private UIInput attachment = null;
private List<AttachmentBean> attachments = new ArrayList<AttachmentBean>();
public void addAddress(ActionEvent event){
attachments.add(new AttachmentBean());
this.updateAddresses();
FacesContext.getCurrentInstance().renderResponse();
System.out.println("adress size:" + attachments.size());
}
public void deleteAddress(ActionEvent event){
int index = data.getRowIndex();
this.updateAddresses();
this.getAttachments().remove(index);
FacesContext.getCurrentInstance().renderResponse();
}
public void updateAddresses(){
System.out.println("adress sizedfdfdfdf:" + attachments.size());
#SuppressWarnings("unchecked")
List<AttachmentBean> list = (ArrayList<AttachmentBean>)data.getValue();
for(int i =0;i<data.getRowCount();i++){
data.setRowIndex(i);
list.get(i).setEmailAddress((String)getAttachment().getSubmittedValue());
}
data.setRowIndex(0);
}
public UIData getData() {
return data;
}
public void setData(UIData data) {
this.data = data;
}
public UIInput getAttachment() {
return attachment;
}
public void setAttachment(UIInput attachment) {
this.attachment = attachment;
}
public List<AttachmentBean> getAttachments() {
return attachments;
}
public void setAttachments(List<AttachmentBean> attachments) {
this.attachments = attachments;
}
}
And the Attachment Class is
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
#ManagedBean
#SessionScoped
public class AttachmentBean implements Serializable {
private static final long serialVersionUID = 1L;
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public AttachmentBean() {
super();
}
}
I am not able to add textBox by clicking the add button. Please help. Thanks in advance.
You need to put the whole in a <h:form>. See also commandButton/commandLink/ajax action/listener method not invoked or input value not updated.
Another major mistake is here:
<h:dataTable ... binding="#{utilBean.data}">
...
<h:inputText ... binding="#{utilBean.attachment}"/>
Remove those binding attributes. UI components are request scoped and yet you're binding them to a session scoped bean. This would fail hard if you open the same page in multiple browser windows in the same session. See also How does the 'binding' attribute work in JSF? When and how should it be used?.
That said, the #ManagedBean #SessionScoped on AttachmentBean is completely unnecessary. Get rid of those annotations. The #SessionScoped on UtilBean is also rather strange. The #ViewScoped is much better at its place here. See also How to choose the right bean scope?
I've set-up a system which allows you to view categories of IT-equipment and their subcategories.
Now I want to be able to add a subcategory to a parentcategory via JPA.
The problem is that my entity is persisted correctly, but it does not show up in the dataTable. I need to start a new session to make it visible.
This is my xhtml-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:f="http://java.sun.com/jsf/core">
<h:head>
<title>Kategorie Tester</title>
<h:outputStylesheet library="css" name="tables.css"/>
<f:metadata>
<f:event type="preRenderView" listener="#{kategorieController.beforeRenderLoadKat}"/>
</f:metadata>
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{kategorieController.reload()}"
var="kat"
styleClass="katview">
<h:column>
<f:facet name="header">
Kategorie
</f:facet>
<h:outputText value="#{kat.titel}"/>
</h:column>
<h:column>
<f:facet name="header">
Unterkategorie
</f:facet>
<h:selectManyCheckbox layout="pageDirection">
<f:selectItems value="#{kat.unterkategorieList}"
var="sub"
itemLabel="#{sub.titel}"
itemValue="#{sub.idunterkategorie}"/>
</h:selectManyCheckbox>
</h:column>
</h:dataTable>
<h:panelGroup>
<h:inputText value="#{kategorieController.titel}"/>
<h:selectOneMenu value="#{kategorieController.kategorie.idkategorie}">
<f:selectItems id="kategorie" value="#{kategorieController.allKats}"
var="kati"
itemLabel="#{kati.titel}"
itemValue="#{kati.idkategorie}"/>
</h:selectOneMenu>
<h:commandButton value="Add" action="#{kategorieController.addSub()}"/>
</h:panelGroup>
</h:form>
</h:body>
</html>
And these are my controllers in order to persist and relaod the data:
KategorieController:
package controller;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Inject;
import model.Kategorie;
import model.Unterkategorie;
#ManagedBean
#SessionScoped
public class KategorieController implements Serializable {
#Inject
private KategorieService katService;
private List<Kategorie> allKats;
// Hinzufügen
private Unterkategorie subkategorie;
private Kategorie kategorie;
private String titel;
public void beforeRenderLoadKat(final ComponentSystemEvent event) {
if (allKats != null) {
allKats.clear();
}
allKats = katService.getAll();
subkategorie = new Unterkategorie();
kategorie = new Kategorie();
}
public void addSub() {
subkategorie.setKategorieId(kategorie);
subkategorie.setTitel(titel);
katService.addSub(this.subkategorie);
}
// GETTERS AND SETTERS
}
KategorieService:
package controller;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import model.Kategorie;
import model.Unterkategorie;
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class KategorieService implements Serializable {
#Inject
private KategorieFacade katFacade;
public List<Kategorie> getAll() {
return katFacade.getAll();
}
public List<Kategorie> addSub(final Unterkategorie sub) {
return katFacade.addSub(sub);
}
}
KategorieFacade:
package controller;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import model.Kategorie;
import model.Unterkategorie;
public class KategorieFacade {
#PersistenceContext
private EntityManager em;
public List<Kategorie> getAll() {
TypedQuery<Kategorie> query = em.createNamedQuery("Kategorie.findAll", Kategorie.class);
return query.getResultList();
}
public List<Kategorie> addSub(final Unterkategorie sub) {
em.persist(sub);
em.flush();
return getAll();
}
}
Any help is appreciated!
Thank you in advance!
Why don't you try to refresh the collection in the addSub() method:
public void addSub() {
subkategorie.setKategorieId(kategorie);
subkategorie.setTitel(titel);
allKats.clear();
allKats.addAll(katService.addSub(this.subkategorie));
}
And completely unrelated to the original question: you're interchanging the concepts Service and Facade with each other.
But I would suggest that instead of putting the getAll() into addSub(), make it void and do another call from the client to the service after doing the insertion.
I have tried a bunch of suggestions after googling but none has so far worked for me. I am trying to display a simple datatable with editable inputText values in each row. table is being populated from database via a usual List of objects. Here is my xhtml page and managed bean
Richfaces 4.2.1, JSF 2 mojarra bundled with JBoss 7.1, JDK 1.6
<rich:dataTable value="#{wlScoreBean.scoreList}" binding="#{wlScoreBean.scoreTable}" var="item" id="table" style="width:100%">
<rich:column>
<f:facet name="header">PARAM NAME</f:facet>
<h:outputText value="#{item.paramName}" />
</rich:column>
<rich:column>
<f:facet name="header">1 Score</f:facet>
<h:inputText value="#{item.name1}" />
</rich:column>
<rich:column>
<f:facet name="header">2 Score</f:facet>
<h:inputText value="#{item.name2}" />
</rich:column>
</rich:dataTable>
<br/>
<h:panelGrid columns="3" id="buttonRow">
<a4j:commandButton value="Save" render="table" execute="#this" action="#{wlScoreBean.update()}">
</a4j:commandButton>
</h:panelGrid>
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.event.ValueChangeEvent;
import org.richfaces.component.UIDataTable;
#ManagedBean(name = "wlScoreBean")
#ViewScoped
public class WS implements Serializable
{
private static final long serialVersionUID = 1L;
private HtmlDataTable scoreTable;
private List<WorkloadScore> scoreList;
public void watchScore(ValueChangeEvent e)
{
System.out.println("old value="+e.getOldValue() + ", New Value="+e.getNewValue());
}
public List<WorkloadScore> getScoreList() {
return scoreList;
}
public void setScoreList(List<WorkloadScore> scoreList) {
this.scoreList = scoreList;
}
#EJB
private WorkloadScoreManagerService wlScoreManager;
public HtmlDataTable getScoreTable() {
return scoreTable;
}
public void setScoreTable(HtmlDataTable scoreTable) {
this.scoreTable = scoreTable;
}
public WorkloadScoreBean()
{
}
#PostConstruct
private void getAllScores()
{
this.scoreList = wlScoreManager.getAllScores();
}
public void update()
{
for (WorkloadScore wls : getScoreList())
{
System.out.println(wls.getParamName()+"="+wls.getPortabilityScore()+","+wls.getVirtualizationScore());
}
//wlScoreManager.update(workloadScore);
}
}
Here's all the things I tried. All of them result in only the OLD VALUES being printed to console in the update() method.
Changed from rich:dataTable to plain old JSF h:dataTable, same result
Bound the dataTable to a Managed Bean property, checked in update() method, old values are being printed here too. I just did a getVlaue() on the UIDataTable object and cast it to List.
The List is supposed to have been updated with changed values from the form, but I do not see it happening. I did make sure to put the MBean in ViewScope.
do you have a h:form outside the datatable? and did you try to replace inputtext with inplaceinput fields?
See answer here https://community.jboss.org/thread/200684?tstart=0
I changed execute=#form and it worked! no need for ValueChangeEvent or messing with dataTable binding. The List values are updated in place and the update method prints the correct value