开发者

How to send a POJO as a callback param using PrimeFaces' RequestContext?

I can send callback param(s) and it works p开发者_StackOverflow中文版erfectly as long as I am only sending some primitive types like String. But the same thing does not work for even the simplest POJO. PrimeFaces guide says that the RequestContext.addCallbackParam() method can handle POJOs and it coverts them into JSON. I don't know why it's not working in my case.

Has anybody done that?


Solution found! ---------------------------------------------------------------------

I did some research and found the answer to this question.

And the solution was to use some JSON library (right now I am using GSON) to convert Java objects to JSON objects.

new Gson().toJson(someJavaObj)

returns string. Just send the string as the param and on the client side using js' eval or some js library's function to turn that into JSON again.

Actually, it was pretty clean and simple.

Sorry I actually did not post the solution. Below is the my solution -

Action method in the backing bean -

public void retrievePieData() { 
    List<String> categories = new ArrayList<String>();

    categories.add("Electronic");
    categories.add("Food");
    categories.add("Liguor");
    categories.add("Stationary");
    categories.add("Mechanical");

    List<Integer> itemCounts = new ArrayList<Integer>();

    itemCounts.add(5);
    itemCounts.add(20);
    itemCounts.add(1);
    itemCounts.add(50);
    itemCounts.add(10);

    RequestContext reqCtx = RequestContext.getCurrentInstance();
    reqCtx.addCallbackParam("categories", new Gson().toJson(categories));
    reqCtx.addCallbackParam("itemCounts", new Gson().toJson(itemCounts));
}

PrimeFaces p:commandButton in the view -

<p:commandLink action="#{pieDataProvider.retrievePieData}" oncomplete="feedPieData(xhr, status, args);"  value="Pie chart demo" update="pieData" />

Javascript function -

function feedPieData(xhr, status, args) {
    var categories = eval('(' + args.categories + ')');
    var itemCounts = eval('(' + args.itemCounts + ')');

    options.xAxis.categories = categories;

    var series = {
         data: []
    };

    series.name = new Date().toString();
    series.data = itemCounts;

    options.series = [series];

    chart = new Highcharts.Chart(options);
}

I would really appreciate and welcome any suggestion or opinion. Thank you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜