Step by step:
Create a backing bean method for updating a String attribute (jsonData) with the numerical array string JSON representation. You will have to:
- Call to an EJB bean or JAX-RS service that returns the data.
- Read the data in a List.
- Convert the List collection to a JSON object and then stringify it, for example using the javax.json package from the standard.
- Update the jsonData model attribute.
In the JSF page you have to include an outputLabel component binded to the jsonData attribute. You can hide it with CSS.
In the JSF page write Javascript code to put the component value in a Javascript variable. You can achieve it with a jQuery selector or in plain Javascript with getElementById function.
Finally you use the Javascript variable in the D3 library.
Note: The use of D3 libraty has been copied from here.
The code in the JSF page would be similar to this:
<h:form id="myForm">
<h:outputLabel id="myLink" value="#{yourBackingBean.jsonData}"
style="display:none;" styleClass="myLink"/>
<div class="someclass">
<h2>Create A Bar Chart With D3 JavaScript</h2>
<div id="bar-chart">
</div>
</div>
<script>
var chartdata = eval(document.getElementById("myForm:myLink").innerHTML);
// you can use jQuery too: $(".myLink").html()
// the size of the overall svg element
var height = 200,
width = 720,
// the width of each bar and the offset between each bar
barWidth = 40,
barOffset = 20;
d3.select('#bar-chart').append('svg')
.attr('width', width)
.attr('height', height)
.style('background', '#dff0d8')
.selectAll('rect').data(chartdata)
.enter().append('rect')
.style({'fill': '#3c763d', 'stroke': '#d6e9c6', 'stroke-width': '5'})
.attr('width', barWidth)
.attr('height', function (data) {
return data;
})
.attr('x', function (data, i) {
return i * (barWidth + barOffset);
})
.attr('y', function (data) {
return height - data;
});
</script>
</h:form>