JSF2 – Ajax rendering of content outside form

Per aggiornare un compontente tramite ajax si utilizza in jsf si utilizza il tag f:ajax:

<f:ajax render=”<nomeComponente>” />

ma quando il compente è fuori dal form si deve utilizzare la sintassi

render=”<nomeForm>:<nomeComponente>”

vediamo un esempio

UserBean.java

package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean
@SessionScoped
public class UserBean {
 private String result = "Hello world";

 public void updateResult() {

  result = "Ciao Mondo";

 }

 public String getResult() {
  return result;
 }

 public void setResult(String result) {
  this.result = result;
 } 
 
 

}



ajaxoutform.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:f="http://java.sun.com/jsf/core"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:ui="http://java.sun.com/jsf/facelets"
 xmlns:p="http://primefaces.org/ui"
 xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head />
<h:body>
 <h:form id="form">
  <h:commandButton id="button" action="#{userBean.updateResult}">
   <f:ajax render=":otherform:result" />
  </h:commandButton>
 </h:form>
 <h:form id="otherform">
  <h:outputText id="result" value="#{userBean.result}" />
 </h:form>

</h:body>
</html>



eseguendo la pagina si ha:



cliccando il tasto, il testo si aggiorna


JSF2 – p:remoteCommand Example Chat Primefaces

p:remoteCommand chiama un metodo di un backing bean (tramite actionlistener) e, fondamentalemnte, fa da trigger ad uno javascript(oncomplete):

<p:remoteCommand name="nextMessage"
actionListener="#{messageBean.firstUnreadMessage}"
oncomplete="javascript:updateMessages(xhr, status, args);" />

Back-End

MessageBean.java

package com;

import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;


@ManagedBean
@ViewScoped
public class MessageBean implements Serializable {



private final List messages;
private Date lastUpdate;
private Message message;

/**
* Creates a new instance of MessageBean
*/
public MessageBean() {
messages = Collections.synchronizedList(new LinkedList());
lastUpdate = new Date(0);
message = new Message();
}

public Date getLastUpdate() {
return lastUpdate;
}

public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}

public Message getMessage() {
return message;
}

public void setMessage(Message message) {
this.message = message;
}


public void firstUnreadMessage(ActionEvent evt) {
RequestContext ctx = RequestContext.getCurrentInstance();

ctx.addCallbackParam("ok", message!=null);
if(message==null)
return;

lastUpdate = message.getDateSent();

ctx.addCallbackParam("user", message.getUser());
ctx.addCallbackParam("dateSent", new Date().toString());
ctx.addCallbackParam("text", message.getMessage());

}

}

Message.java
package com;
import java.io.Serializable;

public class Message implements Serializable {
private Date dateSent;
private String user;
private String message;

public Date getDateSent() {
return dateSent;
}

public void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}
}

Front-End

Chat1.xhtml
<?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>
<title>Chat test!</title>
<script type="text/javascript"
src="#{facesContext.externalContext.requestContextPath}/util.js"></script>

</h:head>

<h:body>
<h:form prependId="false">
<h:panelGrid columns="2">
Name: <p:inputText value="#{messageBean.message.user}" />
Text: <p:inputText
value="#{messageBean.message.message}" />
<p:commandButton type="reset" value="Clear" />
<p:commandButton value="Send!"
actionListener="#{messageBean.sendMessage}" onclick="nextMessage();" />
</h:panelGrid>
<p:remoteCommand name="nextMessage"
actionListener="#{messageBean.firstUnreadMessage}"
oncomplete="javascript:updateMessages(xhr, status, args);" />
</h:form>

<hr />
<h3>Live chat</h3>
<div id="chat"></div>
</h:body>
</html>


util.js

function updateMessages(xhr, status, args) {
if(!args.ok) return;
$('#chat').append('<div class="msg">[' +args.dateSent+ '] <strong>'+args.user+'</strong>: '+args.text+'</div>');
}

Esecuzione

lanciando da browser l’url
http://localhost:8080/JSFProject/faces/chat1.xhtml

si ha una simulazione di chat 


JSF2 – Bean Method Call With Parameter

Un metodo di un bean può ricevere in input parametri da una pagina jsf:
#{bean.method(param)}
Questa  sintassi funziona con Tomcat 7, perchè supporta le EL 2.2 (el-impl-2.2.jar).

passParameter.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:f="http://java.sun.com/jsf/core"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:ui="http://java.sun.com/jsf/facelets"
 xmlns:p="http://primefaces.org/ui"
 xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head/>
<h:body>
 <h:form>
<h:commandButton action="#{passParameterBean.getParameter(gigi)}" />

 </h:form>
</h:body>
</html>
PassParameter.java
package com;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class PassParameterBean {
 
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 
 public String getParameter(String name)
 {
  this.name = name;
  
  return "./passParameterResult.xhtml";
 }

}

PassParameterResult.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:f="http://java.sun.com/jsf/core"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:ui="http://java.sun.com/jsf/facelets"
 xmlns:p="http://primefaces.org/ui"
 xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head />
<h:body>
 <h:form>
  <h:outputText value="#{passParameterBean.name}" />

 </h:form>
</h:body>
</html>


JSF2 Primefaces – p:galleria Example

p:galleria è un tag per la visualizzazione delle immagini:

<p:galleria value=”#{galleriaBean.images}” var=”image” >
    <p:graphicImage value=”/resources/images/#{image}” />
</p:galleria>

Si hanno a disposizione vari effetti:
http://primefaces-rocks.appspot.com/ui/galleria.jsf

Bean java e pagina xhtml

galleria.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:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head/>
<h:body>
<h:form>
<h3>Images1 </h3>  
<p:galleria value=”#{galleriaBean.images}” var=”image” panelWidth=”500″ panelHeight=”313″ effectSpeed=”1000″>  
    <p:graphicImage value=”/resources/images/#{image}” />  
</p:galleria>  
  
<h3>Custom Content</h3>  
<p:galleria id=”contentGalleria” value=”#{galleriaBean.players}” var=”player” panelWidth=”250″ panelHeight=”300″  
            frameWidth=”48″ frameHeight=”65″ effect=”clip”>  
  
    <p:graphicImage id=”playerImage” value=”/resources/images/#{player.photo}” alt=”#{image}” title=”#{player.name}”/>  
    <f:facet name=”content”>  
        <h:panelGrid  columns=”2″ cellpadding=”5″>  
            <f:facet name=”header”>  
                <p:graphicImage value=”/resources/images/#{player.photo}” />  
            </f:facet>  
  
            <h:outputText value=”Name: ” />  
            <h:outputText id=”name” value=”#{player.name}”/>  
  
            <h:outputText value=”Number ” />  
            <h:outputText id=”number” value=”#{player.number}”/>  
  
            <h:outputText value=”Position ” />  
            <h:outputText id=”position” value=”#{player.position}”/>  
        </h:panelGrid>  
    </f:facet>  
  
</p:galleria>  
 </h:form>
</h:body>
</html>

GalleriaBean.java

package com;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import java.util.ArrayList;  
import java.util.List;  
import javax.annotation.PostConstruct;  

@ManagedBean
@SessionScoped
public class GalleriaBean {  
  
    private List<String> images;  
  
    private List<Player> players;  
  
    private Player selectedPlayer;  
  
    @PostConstruct  
    public void init() {  
        images = new ArrayList<String>();  
  
        for(int i=1;i<=12;i++) {  
            images.add(“photoProfile.png”);  
        }  
  
        players = new ArrayList<Player>();  
  
        players.add(new Player(“Messi”, 10, “photoProfile.png”, “CF”));  
        players.add(new Player(“Iniesta”, 8, “photoProfile.png”, “CM”));  
        players.add(new Player(“Villa”, 7, “photoProfile.png”, “CF”));  
        players.add(new Player(“Xavi”, 6, “photoProfile.png”, “CM”));  
        players.add(new Player(“Puyol”, 5, “photoProfile.png”, “CB”));  
    }  
  
    public Player getSelectedPlayer() {  
        return selectedPlayer;  
    }  
  
    public void setSelectedPlayer(Player selectedPlayer) {  
        this.selectedPlayer = selectedPlayer;  
    }  
  
     
    public List<String> getImages() {  
        return images;  
    }  
  
    public List<Player> getPlayers() {  
        return players;  
    }  
}  
  


Esecuzione
Deployando e, da browser, chiamando l’url:

http://localhost:8080/JSFProject/faces/galleria.xhtml

si ottiene:

JSF2 – Load Properties File Dentro Bean

Legge un file di properties (configurationFBM) da dentro un Backing Bean:

package com;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class GalleriaBean {

private ResourceBundle configurationFBM;
private String pathFileUser;

@PostConstruct
public void init() {
FacesContext context = FacesContext.getCurrentInstance();
configurationFBM = context.getApplication().getResourceBundle(context,
“configurationFBM”);
if (this.configurationFBM != null) {
this.pathFileUser = configurationFBM.getString(“pathFileUser”);
}

}

public String getPathFileUser() {
return pathFileUser;
}

public void setPathFileUser(String pathFileUser) {
this.pathFileUser = pathFileUser;
}

}

f:ajax with f:param, JSF2

f:ajax è un tag JSF che aggiunge il meccanismo delle request asincrone a molti componenti UI. 
Per passare dei parametri viene aggiunto il tag f:param
pagina con supporto ajax:


ProvaAjax.xhmtl

<!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://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head/>
<h:body>
<h:form>
<input type=”hidden” name=”id2″ id=”id2″ value=”55″ />
<h:commandLink value=”ssss”>
<f:param name=”id” value=”44″ />
<f:ajax listener=”#{galleriaBean.countListener}”>

</f:ajax>
</h:commandLink>

</h:form>
</h:body>
</html>


nel tag f:ajax:
            – execute=”name”, indica che il componente con id “name” deve essere mandato al server.
            – render=”output”, indica che il componente con id “output” dovrà, dopo la request ajax, essere aggiornato.
            – listener=“#{provaTag.handleEvent}”, indica il metodo del bean da chiamare.


GalleriaBean.java

package com;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

@ManagedBean
@SessionScoped
public class GalleriaBean {

public void countListener(AjaxBehaviorEvent event) {
System.out.println(“test:”);
String id = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get(“id”);
System.out.println(“id:” + id);
}

}

aprendo l’indirizzo: http://localhost:8080/JSFProject/faces/ProvaAjax.xhtml



cliccando sul link “sss” si entra dentro il listener che scrive sulla console:







p:lightBox PrimeFaces JSF2 With Dynamic Images

p:lightBox mostra una sequenza di foto.

Creare una cartella Web-Inf/resources/images con  una immagine chiamata photoProfile.png

Creare i seguenti file:
Photo.java

package com;

public class Photo {

private String img;
private String position;



public Photo() {
super();
// TODO Auto-generated constructor stub
}

public Photo(String img, String position) {
super();
this.img = img;
this.position = position;
}


public String getImg() {
return img;
}

public void setImg(String img) {
this.img = img;
}

public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}

GalleriaBean.java

package com;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class GalleriaBean {

    private List<Photo> images;

    private Photo selectedPlayer;

    @PostConstruct
    public void init() {
        images = new ArrayList<Photo>();

        for(int i=1;i<=12;i++) {
        Photo photo = new Photo();
        photo.setImg(“/resources/images/photoProfile.png”);
        photo.setPosition(“http://localhost:8080/JSFProject/resources/images/photoProfile.png”);
            images.add(photo);
        }

    }

    public Photo getSelectedPlayer() {
        return selectedPlayer;
    }

    public void setSelectedPlayer(Photo selectedPlayer) {
        this.selectedPlayer = selectedPlayer;
    }

   
    public List<Photo> getImages() {
        return images;
    }

    public List<Photo> getPlayers() {
        return images;
    }
}

showPhoto.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:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head>

</h:head>
<h:body>
<h:form>

<p:lightBox styleClass=”imagebox”>
<ui:repeat var=”image” value=”#{galleriaBean.images}”>
<h:outputLink value=”#{image.position}”>
<p:graphicImage value=”#{image.img}”
alt=”Image Description for #{image}” title=”#{image}” />
</h:outputLink>
</ui:repeat>

</p:lightBox>

</h:form>
</h:body>
</html>

l’output sarà:

h:dataTable JSF2

h:dataTable è un tag  per visualizzare  una lista di oggetti in una tabella HTML.
Creare una classe User che contiene le informazioni da visualizzare:

User.java

package com;
public class User {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}

Creare un backing bean

TableExampleBean

package com;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class TableExampleBean {

private List<User> users;

@PostConstruct
public void init() {
users = new ArrayList<User>();

User user = new User();
user.setName(“Paperino”);
user.setSurname(“Rossi”);
users.add(user);

user = new User();
user.setName(“Pippo”);
user.setSurname(“Rossi”);
users.add(user);

user = new User();
user.setName(“Pluto”);
user.setSurname(“Rossi”);
users.add(user);

}

public List<User> getUsers() {
return users;
}

public void setUsers(List<User> users) {
this.users = users;
}

}

Creare la pagina xhtml contenente il tag

showUsers.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:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head>
</h:head>
<h:body>
<h:form>
<h:dataTable var=”user” value=”#{tableExampleBean.users}”>
<h:column>
<h:outputText value=”#{user.name}” />
</h:column>
<h:column>
<h:outputText value=”#{user.surname}” />
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>

Output visualizzato: