in my XHTML page I can't call methods declared in managed bean, I'm new to this platform , I'd like that some one clarifies this to me. I'm working on a JSF 2.1 project with JPA on Eclipse Juno 4.2
here's my managed been code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package managedBean;
import java.util.List;
import javax.ejb.Local;
import model.*;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import service.EmpFacadeLocal;
/**
*
* #author Louuup
*/
#ManagedBean (name= "empbean")
#RequestScoped
#ViewScoped
public class EmpManagedBean {
public Employe emp;
#EJB
public EmpFacadeLocal empfacadelocal;
public Boolean saisie;
private List<Employe> emps;
private String iddd;
private Employe selectedemp;
private List<Employe> filteredemps;
private Employe[] selectedemps;
/**
* Creates a new instance of EmpManagedBean
*/
public EmpManagedBean() {
emps = new ArrayList<Employe>();
}
#PostConstruct
public void initEmp(){
emp = new Employe();
saisie = false;
emps = empfacadelocal.getEmpRq("");
}
public Employe getEmp() {
return emp;
}
public void setEmp(Employe emp) {
this.emp = emp;
}
public Boolean getSaisie() {
return saisie;
}
public void setSaisie(Boolean saisie) {
this.saisie = saisie;
}
public List<Employe> getEmps() {
return emps;
}
public void setEmps(List<Employe> emps) {
this.emps = emps;
}
public String getIddd() {
return iddd;
}
public void setIddd(String iddd) {
this.iddd = iddd;
}
public Employe getSelectedemp() {
return selectedemp;
}
public void setSelectedemp(Employe selectedemp) {
this.selectedemp = selectedemp;
}
public List<Employe> getFilteredemps() {
return filteredemps;
}
public void setFilteredemps(List<Employe> filteredemps) {
this.filteredemps = filteredemps;
}
public Employe[] getSelectedemps() {
return selectedemps;
}
public void setSelectedemps(Employe[] selectedemps) {
this.selectedemps = selectedemps;
}
public void findEmpaff(){
//admin = adminfacadelocal.getAdmin(iddd);
emps = empfacadelocal.getEmpRq("");
}
public void creerEmp(){
System.out.println("azertre ");
empfacadelocal.create(emp);
saisie = true;
}
}
and here is my xhtml page
<!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"
xmlns:p="http://primefaces.org/ui">
<body>
<ui:composition template="./../resource/Template.xhtml">
<ui:define name="title">
<title> Ajout emp</title>
</ui:define>
<ui:define name="page">
<h:form id="dd">
<p:growl id="growl" showDetail="true"/>
<p:panel header="Fiche Emplyé" >
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<h:outputLabel value="Matricule Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{empbean.emp.matEmp}"/>
<h:outputLabel value="Nom Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{empbean.emp.nomEmp}"/>
<h:outputLabel value="Prénom Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{empbean.emp.prenomEmp}"/>
<h:outputLabel value="Date de naissance Employé :"/>
<p:calendar disabled="#{empbean.saisie}" locale="pt" showButtonPanel="true" navigator="true" id="pttCal" value="#{empbean.emp.dateNaisEmp}"/>
<h:outputLabel value="Adresse Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{empbean.emp.adressEmp}"/>
<h:outputLabel value="N° téléph Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{emp.emp.numTelfEmp}"/>
<h:outputLabel value="E-mail Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{empbean.emp.emailEmp}"/>
<h:outputLabel value="N° compte Employé :"/>
<p:inputText disabled="#{empbean.saisie}" value="#{empbean.emp.numCompteEmp}"/>
<p:selectOneMenu disabled="#{empManagedBean.saisie}" value="#{empbean.emp.fonctionEmp}">
<f:selectItem itemLabel="Jardinier" itemValue="Jardinier" />
<f:selectItem itemLabel="Agent d'hygiene" itemValue="Agent d'hygiene" />
<f:selectItem itemLabel="Agent de sécurité" itemValue="Agent de sécurité" />
<f:selectItem itemLabel="Magasinier" itemValue="Magasinier" />
</p:selectOneMenu>
</h:panelGrid><br/>
<p:commandButton disabled="#{empbean.saisie}" value="Valider" update="dd" style="margin-left: 250px;" actionListener="#{empbean. }"/>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
I want call "creerEmp" method in command button's actionlistener like this #{empbean.creerEmp()} but I can't do this , please someone help me
A method for an actionlistener needs to have an ActionEvent parameter. But I think what you want is a normal action which should be fine like this:
<p:commandButton disabled="#{empbean.saisie}" value="Valider"
update="dd" style="margin-left: 250px;" action="#{empbean.creerEmp}"/>
Should work with #{empbean.creerEmp} . ActionEvent parameter is not neccesary.
You should try without composition component firstly to see if your ActionListener method works. Besides I think that You're using composition component incorrectly.
Related
I created a dynamic Form where the user can add multiple calendar input fields by clicking a command button. My Problem is, that the connection between View and Been is broken. Submitting the form returns the Date created previously in the Bean initially and not the Date submitted by the user. How to fix it?
EDIT: Changing a date and extending the form afterwards without saving before leads to losing the changed date(s). Even with the solution with a wrapper object provided by #wittakarn.
EDIT: The ajax snippet seems to be the problem, when I strip that out it works.
DynamicFormBean:
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class DynamicformBean implements Serializable {
private static final Logger LOGGER = Logger.getLogger(DynamicformBean.class.getName());
private List<Date> values;
#PostConstruct
public void init() {
values = new LinkedList<>();
values.add(new Date());
}
public void submit() {
// save values in database
LOGGER.info(values.toString());
}
public void extend() {
values.add(new Date());
}
public void setValues(List<Date> values) {
this.values = values;
}
public List<Date> getValues() {
return values;
}
}
My View: dynamicform.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<f:view 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:body>
<h:form><h2>Dynamicform example</h2>
<ui:repeat value="#{dynamicformBean.values}" var="value">
<p:outputLabel for="mask" value="Mask:" />
<p:calendar id="mask" value="#{value}" pattern="dd.MM.yyyy" mask="true">
<f:convertDateTime pattern="dd.MM.yyyy" timeZone="CET" />
</p:calendar>
<br />
</ui:repeat>
<h:commandButton value="Extend">
<f:ajax listener="#{dynamicformBean.extend}" process="#form" render="#form" />
</h:commandButton>
<h:commandButton action="#{dynamicformBean.submit}" value="Save" />
</h:form>
</h:body>
</f:view>
The log just prints elements with the current date.
I cannot tell in detail why connection between View and Been is broken, but when I wrap object date into Data class as following code. The problem is gone.
xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<f:view 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:head><title>Dynamicform example</title></h:head>
<h:body>
<h:form>
<h2>Dynamicform example</h2>
<ui:repeat value="#{dynamicformBean.values}" var="value">
<p:outputLabel for="mask" value="Mask:" />
<p:calendar id="mask"
value="#{value.date}"
pattern="dd.MM.yyyy" mask="true">
<f:convertDateTime pattern="dd.MM.yyyy" timeZone="CET" />
</p:calendar>
<br/>
</ui:repeat>
<h:commandButton value="Extend">
<f:ajax render="#form"
listener="#{dynamicformBean.extend}"/>
</h:commandButton>
<h:commandButton action="#{dynamicformBean.submit}" value="Save"/>
</h:form>
</h:body>
</f:view>
</html>
managedbean
#ManagedBean(name = "dynamicformBean")
#ViewScoped
public class DynamicformBean implements Serializable {
private static final Logger LOGGER = Logger.getLogger(DynamicformBean.class.getName());
private List<Data> values;
#PostConstruct
public void init() {
values = new LinkedList<Data>();
values.add(new Data());
}
public void submit() {
// save values in database
for (Data data : values) {
LOGGER.info(data.getDate().toString());
}
}
public List<Data> getValues() {
return values;
}
public void setValues(List<Data> values) {
this.values = values;
}
public void extend(AjaxBehaviorEvent event) {
LOGGER.info("extend");
values.add(new Data());
}
}
Data object
import java.io.Serializable;
import java.util.Date;
public class Data implements Serializable {
private Date date;
public Data(){
date = new Date();
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
However, you should use JSF Standard tags h:head. PrimeFaces uses it to include the necessary java script and CSS code for the Ajax works and fancy look'n'feel.
I have as follows:
I have a datatable that prints a historic of mobiles assigned in a determined moment to a list of users, that datatable prints both: assigned and non-assigned, when the administrator wants to edit a particular assignment can change date of assignment, date of expired, number of line, mobile, etc... Well, I make a query for that which only shows mobiles and lines to edit to this user that are NO assigned in that moment for anyone and show the line and terminal that is assign for that user in that moment for if I want to edit some fields relative to his number and terminal and not have to assign another mobile or line because if I do that, line and mobile assigned for that user will not appear for edit and I would be obligated to choose another one.
That's it but I don't know how to load that list of mobiles and list based in the code of assignment to make the filter for my query when it shows up the modal bootstrap form selects retrieve this data according to this code, that's it the code:
asignacion.jsf
<h:dataTable columnClasses="codigo, fechaini, fechafin, terminal, usuario, numero, perfil, asignado" class="table table-striped table-bordered bootstrap-datatable datatable" value="${listaTerminales.listaAsigMovil_2}" var="o">
<h:column class="hide">
<f:facet name="header">
<h:outputText value="Codigo"/>
</f:facet>
<h:outputText value="${o.codigo}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Fecha Asignación"/>
</f:facet>
<h:outputText value="${o.fechaIniStr}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Fecha Baja"/>
</f:facet>
<h:outputText value="${o.fechaFinStr}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Terminal"/>
</f:facet>
<h:inputHidden class="idTerminal" value="${o.codigoTerminal.codigo}" />
<h:outputText value="${o.codigoTerminal.marca} ${o.codigoTerminal.modelo}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Usuario"/>
</f:facet>
<h:outputText value="${o.dni.dni}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Número"/>
</f:facet>
<h:outputText value="${o.codigoNumero.numero}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Perfil"/>
</f:facet>
<h:inputHidden class="idPerfil" value="${o.codigoPerfil.codigo}" />
<h:outputText value="${o.codigoPerfil.descripcion}"/>
</h:column>
<c:if test="${rol == 'administrador'}">
<h:column>
<f:facet name="header">
<h:outputText value="Asignado"/>
</f:facet>
<h:outputText value="${o.asignado}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Acciones"/>
</f:facet>
<a data-toggle='modal' href='#asig-movil' class='btn btn-success edit'>
<i class='icon3-edit icon-white'></i>Editar</a>
</h:column>
</c:if>
</h:dataTable>
<!-- start modal -->
<div class="hide fade modal" id="asig-movil">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Editar Datos</h3>
</div>
<h:form class="form-horizontal well" id="form-asig-movil">
<div class="modal-body">
<fieldset>
<h:inputHidden id="codigo-form" value="#{terminalesBean.codigoAsig}">
</h:inputHidden>
<h:inputHidden id="dni-form" value="#{listaTerminales.dni}"></h:inputHidden>
<h4>Asignado: </h4><h:selectOneRadio layout="lineDirection" id="asignado-form" value="#{listaTerminales.codAsignado}">
<f:selectItem id="y" itemLabel="SI" itemValue="S"/>
<f:selectItem id="n" itemLabel="NO" itemValue="N"/>
</h:selectOneRadio>
<h4>Número de Teléfono: </h4><h:selectOneMenu class="validate[required]" id="numero-form" value="#{listaTerminales.codigoNumero}">
<f:selectItems var="l" itemLabel="#{l.numero}" itemValue="#{l.codigo}" value="#{lineasBean.listaLineasNoAsig}" />
</h:selectOneMenu>
<h4>Terminal: </h4><h:selectOneMenu class="validate[required]" id="terminal-form" value="#{listaTerminales.codigoTerminal}">
<f:selectItems var="t" itemLabel="#{t.marca} #{t.modelo}" itemValue="#{t.codigo}" value="#{terminalesBean.terminalesMovilAndAsig}" />
</h:selectOneMenu>
<h4>Perfil </h4><h:selectOneMenu class="validate[required]" id="perfil-form" value="#{listaTerminales.codigoPerfil}">
<f:selectItems var="p" itemLabel="#{p.descripcion}" itemValue="#{p.codigo}" value="#{perfilBean.listaPerfiles}" />
</h:selectOneMenu>
<h4>Fecha asignación: </h4><h:inputText class="validate[required]" id="fechaini-form" value="#{listaTerminales.fechaAsig}"></h:inputText>
<h4>Fecha finalización: </h4><h:inputText class="validate[required]" id="fechafin-form" value="#{listaTerminales.fechaFin}"></h:inputText>
</fieldset>
</div>
<div class="modal-footer">
Cancelar
<p:commandButton id="okInsertar" onclick="if($('#form-asig-movil').validationEngine('validate')===false){return false;}"
styleClass="btn btn-primary ok" value="Ok" action="#{listaTerminales.modificar()}"
oncomplete="checkCRUD(xhr, status, args)">
</p:commandButton>
</div>
</h:form>
</div>
<!-- end modal -->
terminalesBean.java
package app.bean;
import app.dao.TerminalFacade;
import app.entity.Terminal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import org.primefaces.context.RequestContext;
/**
*
* #author Usuario
*/
#ManagedBean
#RequestScoped
#ViewScoped
public class terminalesBean {
#EJB
private TerminalFacade termFac;
private int codigo;
private String fecha_alta;
private Date fecha_alta_date;
private String marca;
private String modelo;
private String configuracion;
private int sn;
private List<Terminal> terminales;
private int codigoAsig;
public int getCodigo(){
return this.codigo;
}
public void setCodigo(int codigo){
this.codigo = codigo;
}
public String getFechaAlta(){
SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy");
if(fecha_alta_date!=null)
return formatoFecha.format(fecha_alta_date);
return null;
}
public void setFechaAlta(String fecha){
SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy");
try {
this.fecha_alta_date = formatoFecha.parse(fecha);
this.fecha_alta = fecha;
} catch (ParseException ex) {
Logger.getLogger(lineasBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getMarca(){
return this.marca;
}
public void setMarca(String marca){
this.marca = marca;
}
public String getModelo(){
return this.modelo;
}
public void setModelo(String modelo){
this.modelo = modelo;
}
public String getConfiguracion(){
return this.configuracion;
}
public void setConfiguracion(String configuracion){
this.configuracion = configuracion;
}
public int getSN(){
return this.sn;
}
public void setSN(int sn){
this.sn = sn;
}
public void setCodigoAsig(int codigoAsig){
this.codigoAsig = codigoAsig;
}
public int getCodigoAsig(){
return this.codigoAsig;
}
public List<Terminal> getTerminales(){
terminales = (List<Terminal>)termFac.findAll();
return this.terminales;
}
public List<Terminal> getTerminalesFijoAndAsig(){
terminales = (List<Terminal>)termFac.findByFijoAndAsig(this.codigoAsig);
return this.terminales;
}
public List<Terminal> getTerminalesMovilAndAsig(){
terminales = (List<Terminal>)termFac.findByMovilAndAsig(this.codigoAsig);
return this.terminales;
}
public void setTerminales(List<Terminal> terminales){
this.terminales = terminales;
}
public void borrar(){
Terminal t = new Terminal();
t = termFac.find(codigo);
termFac.delete(t);
}
public void insert(){
Terminal t;
t =(Terminal)termFac.findbysn(sn);
if(t == null && this.sn != 0){
t = new Terminal();
//t.setCodigo(codigo);
t.setFechaAlta(new Date());
t.setConfiguracion(configuracion);
t.setMarca(marca);
t.setModelo(modelo);
t.setSn(sn);
termFac.insert(t);
}
else{
t.setConfiguracion(configuracion);
t.setMarca(marca);
t.setModelo(modelo);
t.setSn(sn);
termFac.edit(t);
}
RequestContext reqCtx = RequestContext.getCurrentInstance();
reqCtx.addCallbackParam("codigo", t.getCodigo());
reqCtx.addCallbackParam("fecha_alta", t.getFechaAltaStr());
reqCtx.addCallbackParam("marca", t.getMarca());
reqCtx.addCallbackParam("modelo", t.getModelo());
reqCtx.addCallbackParam("configuracion", t.getConfiguracion());
reqCtx.addCallbackParam("sn", t.getSn());
}
public terminalesBean() {
}
}
What I want is pass the ${o.codigo} parameter to method setCodigAsig() for then make the filter in method getTerminalesMovilAndAsig() and in the modal load load the content with ids "numero-form" and "terminal-form", how can I do this when click Edit in each row of the datatable and load modal form of this content dynamically according with this code?
Regards!
I would like to do such table with editing like here -> http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=dataTable&sample=dataTableEdit&skin=blueSky . The problem ist that, when I do changes in editPane (popupPanel) they are not remembered in private OsobaTelefon edytujOsobe. This make update impossible via JPA. I have all getters and setters and class OsobaTelefon implements Serializable.
#ManagedBean(name = "administrator")
#ViewScoped
#SessionScoped
public class Administrator implements Serializable
#EJB
private UzytkownikFacade uzytkownikFacade;
private static final long serialVersionUID = 1L;
#EJB
private OsobaFacade osobaFacade;
private Osoba osobaAdmina;
private int numerStrony = 1;
private Uzytkownik uzytkownik;
private List<Osoba> listaOsob;
private static final int CLIENT_ROWS_IN_AJAX_MODE = 10;
private int clientRows;
private int wybranaOsoba;
private OsobaTelefon edytujOsobe; //it doesn't remember the changes made in editPane
private List<OsobaTelefon> osobyITelefony;
/**
* Creates a new instance of Administrator
*/
public Administrator() {
}
public void aktualizacjaWybranejOsoby() {
this.osobyITelefony.set(this.wybranaOsoba, this.edytujOsobe);
Osoba nowaOsoba = new Osoba();
List<Telefon> nowaListaTelefonow = new ArrayList<Telefon>();
OsobaTelefon osobaTelefon = this.osobyITelefony.get(this.wybranaOsoba);
int o = this.osobyITelefony.get(this.wybranaOsoba).getIdosoby();
int of = this.osobyITelefony.get(this.wybranaOsoba).getIdtelefonu();
System.out.println("Wybrana osoba ID " + o);
System.out.println("Wybrane ID fona " + of);
boolean znalezionoOsobe = false;
Iterator<Osoba> iteOs = this.listaOsob.iterator();
while (!znalezionoOsobe && iteOs.hasNext()) {
Osoba os = iteOs.next();
if (os.getIdosoba() == o) {
znalezionoOsobe = true;
nowaOsoba.setIdosoba(os.getIdosoba());
nowaOsoba.setImie(osobaTelefon.getImie());
nowaOsoba.setNazwisko(osobaTelefon.getNazwisko());
nowaOsoba.setKodpocztowy(osobaTelefon.getKodpocztowy());
nowaOsoba.setMiejscowosc(osobaTelefon.getMiejscowosc());
nowaOsoba.setUlica(osobaTelefon.getUlica());
nowaOsoba.setUzytkownikList(os.getUzytkownikList());
Telefon nowyTelefon = new Telefon();
for (Telefon tel : os.getTelefonList()) {
if (tel.getIdtelefon() == of) {
nowyTelefon.setFkIdosoba(nowaOsoba);
nowyTelefon.setIdtelefon(of);
nowyTelefon.setNumer(this.edytujOsobe.getNumer());
System.out.println("Nr tel. "+tel.getNumer());
nowyTelefon.setOpis(this.edytujOsobe.getOpis());
nowyTelefon.setZastrzezony(this.edytujOsobe.getZastrzezony());
nowaListaTelefonow.add(nowyTelefon);
} else {
nowaListaTelefonow.add(tel);
}
}
nowaOsoba.setTelefonList(nowaListaTelefonow);
this.osobaFacade.aktualizujOsoba(nowaOsoba);
this.pobierzOsobyDoTabeli();
}
}
}
public List<Osoba> pobierzOsobyDoTabeli() {
//getting people with phone to List<OsobaTelefon> works good
}
public void switchAjaxLoading(ValueChangeEvent event) {
this.clientRows = (Boolean) event.getNewValue() ? CLIENT_ROWS_IN_AJAX_MODE : 0;
}
public void zapelnijListeTelefonow() {
//getting people phone number to List<Phone> works good
}
public void usunOsobe() {
//deleting people works good
}
}
The XHTML
<a4j:status onstart="#{rich:component('statPane')}.show()" onstop="#{rich:component('statPane')}.hide()" />
<h:form id="formProjekty">
<rich:dataTable value="#{administrator.osobyITelefony}"
var="pr"
iterationStatusVar="ite"
id="table"
rows="8" >
<rich:column width="auto">
<f:facet name="header">Imię</f:facet>
<h:outputText value="#{pr.imie}" />
</rich:column>
<rich:column>
<a4j:commandLink styleClass="no-decor"
render="editGrid"
execute="#this"
oncomplete="#{rich:component('editPane')}.show()">
<h:graphicImage library="img" name="edit.gif" alt="Edycja"/>
<a4j:param value="#{ite.index}"
assignTo="#{administrator.wybranaOsoba}" />
<f:setPropertyActionListener target="#{administrator.edytujOsobe}"
value="#{pr}" />
</a4j:commandLink>
<a4j:commandLink styleClass="no-decor"
execute="#this"
render="#none"
oncomplete="#{rich:component('confirmPane')}.show()">
<h:graphicImage library="img" name="delete.gif" alt="Usuń"/>
<a4j:param value="#{ite.index}"
assignTo="#{administrator.wybranaOsoba}" />
<f:setPropertyActionListener target="#{administrator.edytujOsobe}"
value="#{pr}" />
</a4j:commandLink>
</rich:column>
<f:facet name="footer">
<rich:dataScroller page="#{administrator.numerStrony}" />
</f:facet>
</rich:dataTable>
<a4j:jsFunction name="remove"
action="#{administrator.usunOsobe()}"
render="table"
execute="#this"
oncomplete="#{rich:component('confirmPane')}.hide();" />
<a4j:jsFunction name="edycja"
action="#{administrator.aktualizacjaWybranejOsoby()}"
render="table"
execute="#this"
oncomplete="#{rich:component('editPane')}.hide();" />
<rich:popupPanel id="statPane" autosized="true">
<h:graphicImage library="img" name="ai.gif" alt="Czekaj"/>
Proszę czekać...
</rich:popupPanel>
<rich:popupPanel id="confirmPane" autosized="true">
Czy na pewno usunać?
<a4j:commandButton value="Tak" onclick="remove();
return false;" />
<a4j:commandButton value="Nie"
onclick="#{rich:component('confirmPane')}.hide();
return false;" />
</rich:popupPanel>
<rich:popupPanel header="Edycja Osoby"
id="editPane"
domElementAttachment="parent" width="180" height="420">
<h:panelGrid columns="1" id="editGrid">
<h:panelGroup >
<h:outputText value="Imię" /><br />
<h:inputText value="#{administrator.edytujOsobe.imie}" >
<f:validateLength maximum="32" minimum="3"/>
</h:inputText>
</h:panelGroup>
</h:panelGrid><br/>
<a4j:commandButton value="Aktualizuj"
onclick="edycja(); return false;"/>
<a4j:commandButton value="Anuluj"
onclick="#{rich:component('editPane')}.hide();
return false;" />
</rich:popupPanel>
</h:form>
if you can change it then make your Aktualizuj a4j-link a little bit easier. Just try that:
<a4j:commandButton value="Aktualizuj"
onclick="#{rich:component('editPane')}.hide();"
action="#{administrator.aktualizacjaWybranejOsoby()}" render="table"/>
and put an a4j:region about your inputText and your link to send only the required values:
<rich:popupPanel header="Edycja Osoby"
id="editPane"
domElementAttachment="parent" width="180" height="420">
<a4j:region>
<h:panelGrid columns="1" id="editGrid">
<h:panelGroup >
<h:outputText value="Imię" /><br />
<h:inputText value="#{administrator.edytujOsobe.imie}" >
<f:validateLength maximum="32" minimum="3"/>
</h:inputText>
</h:panelGroup>
</h:panelGrid><br/>
<a4j:commandButtonvalue="Aktualizuj" onclick="# {rich:component('editPane')}.hide();"action="#{administrator.aktualizacjaWybranejOsoby()}" render="table"/>
<a4j:commandButton value="Anuluj"
onclick="#{rich:component('editPane')}.hide();
return false;" />
</a4j:region>
</rich:popupPanel>
I also add a render="table" to the Aktualizuj a4j:link to update the value in the datatable
I am testing the PrimeFaces example avaible at http://www.primefaces.org/showcase/ui/dialogLogin.jsf . I correctly imported PrimeFaces and JSF 2.1 in Eclipse Dyamic web project, but after filling the form when I try to do the login I get the following error:
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.el.MethodNotFoundException: Method not found: classi.LoginBean#ee03ec.login()
javax.faces.webapp.FacesServlet.service(FacesServlet.java:229)
root cause
org.apache.myfaces.view.facelets.el.ContextAwareMethodNotFoundException: javax.el.MethodNotFoundException: Method not found: classi.LoginBean#ee03ec.login()
org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:104)
javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:88)
javax.faces.event.ActionEvent.processListener(ActionEvent.java:51)
javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:418)
javax.faces.component.UICommand.broadcast(UICommand.java:103)
javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1028)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:286)
javax.faces.component.UIViewRoot._process(UIViewRoot.java:1375)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:752)
org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:38)
org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
root cause
javax.el.MethodNotFoundException: Method not found: classi.LoginBean#ee03ec.login()
org.apache.el.util.ReflectionUtil.getMethod(ReflectionUtil.java:225)
org.apache.el.parser.AstValue.invoke(AstValue.java:253)
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:96)
javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:88)
javax.faces.event.ActionEvent.processListener(ActionEvent.java:51)
javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:418)
javax.faces.component.UICommand.broadcast(UICommand.java:103)
javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1028)
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:286)
javax.faces.component.UIViewRoot._process(UIViewRoot.java:1375)
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:752)
org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:38)
org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.21 logs.
Apache Tomcat/7.0.21
LoginBean.java is:
package classi;
import java.awt.event.ActionEvent;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
#ManagedBean(name="loginBean")
#SessionScoped
public class LoginBean
{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void login(ActionEvent actionEvent) {
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg = null;
boolean loggedIn = false;
if(username != null &&&& username.equals("admin") && password != null && password.equals("admin")) {
loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
} else {
loggedIn = false;
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid credentials");
}
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
}
}
login.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"
xmlns:p="http://primefaces.org/ui">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<h:outputLink id="loginLink" value="javascript:void(0)" onclick="dlg.show()" title="login">
<p:graphicImage value="/images/login.png" />
</h:outputLink>
<p:growl id="growl" showDetail="true" life="3000" />
<p:dialog id="dialog" header="Login" widgetVar="dlg">
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" value="Username:" />
<p:inputText value="#{loginBean.username}"
id="username" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<h:inputSecret value="#{loginBean.password}"
id="password" required="true" label="password" />
<f:facet name="footer">
<p:commandButton id="loginButton" value="Login" update=":growl"
actionListener="#{loginBean.login}"
oncomplete="handleLoginRequest(xhr, status, args)"/>
</f:facet>
</h:panelGrid>
</h:form>
</p:dialog>
<script type="text/javascript">
function handleLoginRequest(xhr, status, args) {
if(args.validationFailed || !args.loggedIn) {
jQuery('#dialog').effect("shake", { times:3 }, 100);
} else {
dlg.hide();
jQuery('#loginLink').fadeOut();
}
}
</script>
</body>
</html>
You have a bad import, replace :
import java.awt.event.ActionEvent;
with
import javax.faces.event.ActionEvent;
Also, is that &&&& working?! Maybe you have a special compiler if it doesn't give you error :)
if(username != null &&&& username.equals("admin") && password != null && password.equals("admin"))
I have a problem with the propagation of a long running conversation when I redirect the view by the handleNavigation() method. Here is my test code:
I have a conversationscoped bean and two views:
conversationStart.xhtml is called in Browser with URL
http://localhost/tests/conversationStart.jsf?paramTestId=ParameterInUrl
<!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:metadata>
<f:viewParam name="paramTestId" value="#{conversationTest.fieldTestId}" />
<f:event type="preRenderView" listener="#{conversationTest.preRenderView}" />
</f:metadata>
<h:head>
<title>Conversation Test</title>
</h:head>
<h:body>
<h:form>
<h2>Startpage Test Conversation with Redirect</h2>
<h:messages />
<h:outputText value="Testparameter: #{conversationTest.fieldTestId}"/><br />
<h:outputText value="Logged In: #{conversationTest.loggedIn}"/><br />
<h:outputText value="Conversation ID: #{conversationTest.convID}"/><br />
<h:outputText value="Conversation Transient: #{conversationTest.convTransient}"/><br />
<h:commandButton action="#{conversationTest.startLogin}" value="Login ->" rendered="#{conversationTest.loggedIn==false}" /><br />
<h:commandLink action="/tests/conversationLogin.xhtml?faces-redirect=true" value="Login ->" rendered="#{conversationTest.loggedIn==false}" /><br />
</h:form>
<h:link outcome="/tests/conversationLogin.xhtml" value="Login Link" rendered="#{conversationTest.loggedIn==false}">
<f:param name="cid" value="#{conversationTest.convID}"></f:param>
</h:link>
</h:body>
</html>
The Parameter is written to the beanfield and displayed in the view correctly. There are 3 different possibilities to navigate to the next View. All 3 work fine. The beanfield shows up the next view (conversationLogin.xhtml) too:
<!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>Conversation Test</title>
</h:head>
<h:body>
<h:form>
<h2>Loginpage Test Conversation with Redirect</h2>
<h:messages />
<h:outputText value="Testparameter: #{conversationTest.fieldTestId}"/><br />
<h:outputText value="Logged In: #{conversationTest.loggedIn}"/><br />
<h:outputText value="Conversation ID: #{conversationTest.convID}"/><br />
<h:outputText value="Conversation Transient: #{conversationTest.convTransient}"/><br />
<h:commandButton action="#{conversationTest.login}" value="Login And Return" /><br />
</h:form>
</h:body>
</html>
When I return to the Startpage by clicking the button the conversation bean still contains all values. So everything is fine. Here is the bean:
package test;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Inject;
import javax.inject.Named;
#Named
#ConversationScoped
public class ConversationTest implements Serializable{
private static final long serialVersionUID = 1L;
final String CONVERSATION_NAME="longRun";
#Inject Conversation conversation;
private boolean loggedIn;
private String fieldTestId;
#PostConstruct
public void init(){
if(conversation.isTransient()){
conversation.begin(CONVERSATION_NAME);
System.out.println("New Conversation started");
}
loggedIn=false;
}
public String getConvID(){
return conversation.getId();
}
public boolean isConvTransient(){
return conversation.isTransient();
}
public boolean getLoggedIn(){
return loggedIn;
}
public String startLogin(){
return "/tests/conversationLogin.xhtml?faces-redirect=true";
}
public String login(){
loggedIn=true;
return "/tests/conversationStart.xhtml?faces-redirect=true";
}
public void preRenderView(ComponentSystemEvent ev) {
// if(!loggedIn){
// System.out.println("Will redirect to Login");
// FacesContext ctx = FacesContext.getCurrentInstance();
// ctx.getApplication().getNavigationHandler().handleNavigation(ctx, null, "/tests/conversationLogin.xhtml?faces-redirect=true");
// ctx.renderResponse();
// }
}
public void setFieldTestId(String fieldTestId) {
System.out.println("fieldTestID was set to: "+fieldTestId);
this.fieldTestId = fieldTestId;
}
public String getFieldTestId() {
return fieldTestId;
}
}
Now comes the problem
As soon as I try to redirect the page in the preRenderView method of the bean (just uncomment the code in the method), using handleNavigation() the bean is created again in the next view instead of using the already created instance. Although the cid parameter is propagated to the next view !
Has anybody an idea what's wrong ?
best regards
Thomas