Best way to pass data from Java / JSF2 bean to Javascript / jQuery Components as return values

I'm having problems using the best method of transferring data from a Java backing / managed bean to a jQuery / Javascript component like Highcharts, so my web application creates / displays data in real-time dynamic mode, I'm pretty solid on the Java side, but I have fairly limited knowledge of JavaScript / jQuery, which is obviously where I fall. As far as I read, the best way is to Ajaxify a hidden field in my web application and pass in an object or JSON string? into it, and then pass that value to my JS component.

Firstly, it seems a little time consuming since I would have an Ajax call to update the JSON data, and then a setInterval call to read the data back into the JS component? I was hoping I could pass the data directly to the JS component ...

In any case, someone can just strengthen my knowledge and tell me a good tried and tested method if it differs from the above ... Guides / Demos will also be weighted !!

I also use Primeface 2.2.1, if it affects the proposed methodology?

Greetings

Ally

UPDATE:

The code is below, but I just want to describe what I am trying to achieve quickly: effectively I am trying to implement a dynamic Highcharts chart using the simple count ++ function from my bean support. Obviously, down the line I will use the channel in real time to provide this data, but at the moment I'm just trying to get Highcharts to work based on changing the information from my JSF bean support.

Here is my simple function of counting and converting to JSON (I'm not sure if the JSON method is really necessary, since only 1 value (int) is passed, but I would like to keep this method, because I'm sure I will use other parts of the web more widely applications):

public class TestBean { private int output; public TestBean() { output = 1; } public int getOutput() { return output; } public void setOutput(int output) { this.output = output; } public void update() { setOutput(getOutput() + 1); } public void prepareChartDate() { // Produce you JSON string (I use Gson here) RequestContext reqCtx = RequestContext.getCurrentInstance(); reqCtx.addCallbackParam("chartData", new Gson().toJson(output)); } } 

Highcharts External JS File, again it’s worth noting that I saved the series function at the bottom of the chart in order to build / fill the chart before I start adding the values ​​obtained from JSF Beans:

 Highcharts.setOptions({ global: { useUTC: false } }); var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { backgroundColor: "#F8F0DB", renderTo: 'containerHigh', defaultSeriesType: 'area', margin: 10, marginLeft:30, marginBottom:17, zoomType: 'y', events: { load: updateChartData } }, title: { text: 'Feed Flow Rate ' }, xAxis: { type: 'datetime', tickPixelInterval: 150 }, yAxis: { title: { text: '' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+ Highcharts.numberFormat(this.y, 2); } }, legend: { enabled: false }, exporting: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: [0, 0, 0, 100], stops: [ [0, Highcharts.getOptions().colors[0]], [1, 'rgba(2,0,0,0)'] ] }, lineWidth: 1, marker: { enabled: false, states: { hover: { enabled: true, radius: 5 } } }, shadow: false, states: { hover: { lineWidth: 1 } } } }, series: [{ name: 'Random data', data: (function() { // generate an array of random data var data = [], time = (new Date()).getTime(), i; for (i = -19; i <= 0; i++) { data.push({ x: time + i * 10000, y: 50 * Math.random() }); } return data; })() }] }); }); 

And the inline JS function stored on my XHTML page:

It works:

  function updateChartData(xhr, status, args) { var series = this.series[0]; setInterval(function() { var x = (new Date()).getTime() y = 50 * Math.random(); series.addPoint([x, y], true, true); }, 1000) //parse it, process it and load it into the chart } 

but when I try to pass the bean value:

  function updateChartData(xhr, status, args) { var jsonString = args.chartData var series = this.series[0]; setInterval(function() { var x = (new Date()).getTime() y = jsonString series.addPoint([x, y], true, true); }, 1000) //parse it, process it and load it into the chart } 

This does not work...

I also try both remoteCommand and polling to get the diagram to work, none of which I failed:

  <h:form> <p:commandButton value="update" action="#{testBean.update}" update="beanvalue"/> <h:outputText value="#{testBean.output}" id="beanvalue"/> <br /> <h:outputText value="#{testBean.output}" id="chartValue"/> <br /> <p:commandButton value="Load" type="button" onclick="fetchChartData();"/> <p:remoteCommand name="fetchChartData" action="#{testBean.prepareChartDate()}" oncomplete="updateChartTest(xhr, status, args);"/> </h:form> 

As I said before Bhesh, your help was widely appreciated, and it would be great!

Greetings

Ally

+7
source share
1 answer

If you are using PrimeFaces 2.2.1 , it should be pretty easy for you to achieve what you are trying to do.

PF has a component p:remoteCommand , with which you can Ajaxicaly call the managed bean method.

 <h:form id="frmIrsChartData"> <p:remoteCommand name="fetchChartData" action="#{chartManagedBean.prepareChartData()}" oncomplete="updateChartData(xhr, status, args);"/> </h:form> 

And in the prepareChartData() method, you create a JSON string and use the RequestContext provided by PF to send it to the client:

 public void prepareChartDate() { // Produce you JSON string (I use Gson here) RequestContext reqCtx = RequestContext.getCurrentInstance(); reqCtx.addCallbackParam("chartData", jsonString); } 

And in the Javascript callback function updateChartData(xhr, status, args) you can process the JSON response and load it into the diagram:

 function updateChartData(xhr, status, args) { var jsonResponse = args.chartData; //parse it, process it and load it into the chart } 

And to update the chart periodically, simply use the Javascript setInterval or setTimeout and pass in the name remoteCommand , which is actually a Javascript function.

 setInterval("fetchChartData()", 5000); 

How am i doing this.

PF also has another component p:poll , which simplifies the implementation of live charts.

Update:

You are wrong. On

What you need to do is prepare the document first, and then start the survey.

 $(document).ready(function() { chart = new Highcharts.Chart({ //.... }); // start your poll here }); 

The p:poll updateChartData(xhr, status, args) callback function must be global so that polling can call it in the oncomplete event.

 function updateChartData(xhr, status, args) { var jsonResponse = args.chartData; //parse it, process it and load it into the chart //you will load data into the same chart created in document-ready } 

And when you use polling, you do not need setTimeout or setInterval .

Update 2:

First of all, in the updateChartData function updateChartData you must update the created chart :

 function updateChartData(xhr, status, args) { var series = chart.series[0]; // <--- no more this instead global variable "chart" var newData = args.chartData; var x = (new Date()).getTime() var y = eval('(' + newData + ')'); series.addPoint([x, y], true, true); } 

Further, updateChartData is a callback function, so do not call it yourself, it is called by a remote command every time the request is completed.

And give the remote command a separate form:

 <h:form> <p:remoteCommand name="fetchChartData" action="#{testBean.prepareChartDate()}" oncomplete="updateChartData(xhr, status, args);"/> </h:form> 

Note in oncomplete="updateChartTest(xhr, status, args);" in your code, the callback function should be updateChartTest instead of updateChartTest .

Start adiax polling after completion of the graph.

 events: { load: function() { setInterval("fetchChartData()", 5000); //update the chart every 5 seconds } } 

For testing purposes only, try returning a random value from your managed bean:

 public void prepareChartDate() { // Produce you JSON string (I use Gson here) RequestContext reqCtx = RequestContext.getCurrentInstance(); reqCtx.addCallbackParam("chartData", new Random().nextInt(500)); } 
+16
source

All Articles