Trick JavaServer Faces, load your bean data from the client side

David Dal Busco
Nov 4, 2019 · 6 min read
Image for post
Image for post
Photo by Shawn Pang on Unsplash

Before We Start


Getting Started

Workflow


1. Fetch data from the 3rd party API using Javascript

<!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>Random dog</title>
</h:head>

<h:body>
<script type="text/javascript">
const randomDog = async () => {
const rawResponse =
await fetch('https://dog.ceo/api/breeds/image/random');

if (!rawResponse || !rawResponse.ok) {
console.error(rawResponse);
return;
}

const result = await rawResponse.text();
};
</script>
<h:form>
<p:remoteCommand name="loadResult"/>
<p:commandButton value="Load a random dog"
onclick="randomDog();">
<f:ajax execute="@form" render="@none" />
</p:commandButton>
</h:form>
</h:body></html>

2. Pass the results to the bean

import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Named;

@Named("dogs")
@ViewScoped
public class DogsBean implements Serializable {

public void load() {
// TODO load the data to object values
}

}
<h:form>
<p:remoteCommand name="loadResult"
action="#{dogs.load()}"
process="@this" update="@form"/>
</h:form>
<script type="text/javascript">
// same code as above
const result = await rawResponse.text(); loadResult([{
name: 'dog',
value: result
}]);
};
</script>
public void load() {
final String jsonData =
FacesContext.getCurrentInstance()
.getExternalContext()
.getRequestParameterMap()
.get("dog");
}

3. Parse the information to bean object values

{
"message":
"https://images.dog.ceo/breeds/coonhound/n02089078_2794.jpg",
"status": "success"
}
import java.io.Serializable;

public class DogDTO implements Serializable {

private String message;
private String status;

public String getMessage() {
return message;
}

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

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}
}
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
import java.io.Serializable;

import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Named("dogs")
@ViewScoped
public class DogsBean implements Serializable {

private DogDTO dog;

public void load() {
final String jsonData =
FacesContext.getCurrentInstance()
.getExternalContext()
.getRequestParameterMap()
.get("dog");

final Gson gson = new GsonBuilder().create();

dog = gson.fromJson(jsonData, DogDTO.class);
}

public DogDTO getDog() {
return dog;
}
}

4. Display the bean values on the client side

<h:form>
<p:outputPanel layout="block" rendered="#{dogs.dog != null}">
<img src="#{dogs.dog.message}" alt="A random dog"/>
</p:outputPanel>
</h:form>
mvn clean install && mvn wildfly:run
Image for post
Image for post
So much doggy 😍

5. Init the page with a data

@PostConstruct
public void init() {
PrimeFaces.current().executeScript("randomDog();");
}
Image for post
Image for post
An initial doggy and so much other doggy 😍

Cherry on the cake 🍒🎂

The Startup

Medium's largest active publication, followed by +687K people. Follow to join our community.

Sign up for Top Stories

By The Startup

A newsletter that delivers The Startup's most popular stories to your inbox once a month. Take a look

Create a free Medium account to get Top Stories in your inbox.

David Dal Busco

Written by

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic Zürich Meetup

The Startup

Medium's largest active publication, followed by +687K people. Follow to join our community.

David Dal Busco

Written by

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic Zürich Meetup

The Startup

Medium's largest active publication, followed by +687K people. Follow to join our community.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store