Step by step:
To update a String attribute (jsonData) with the numerical array string JSON representation, create a backing bean method. This method should:
- Invoke an EJB bean or JAX-RS service to retrieve the data.
- Read and store the data in a List.
- Convert the List collection into a JSON object, then stringify it using a package like javax.json from the standard.
- Update the jsonData model attribute accordingly.
In your JSF page, include an outputLabel component that is bound to the jsonData attribute. You can hide this component using CSS.
Add Javascript code to the JSF page to extract the value of the component and store it in a Javascript variable. This can be done using a jQuery selector or plain Javascript with getElementById function.
Finally, utilize the Javascript variable in the D3 library for visualization purposes.
Note: The D3 library usage has been referenced from here.
A sample code snippet in the JSF page may look 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);
var height = 200,
width = 720,
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>