如何在JSF中将列表传递给javascript [英] How to pass a List to javascript in JSF

查看:107
本文介绍了如何在JSF中将列表传递给javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个JSF项目而苦苦挣扎. 在我的服务中,我检索了一个自定义对象的列表(在这里为Sales),并且必须将其传递到jsf视图中,尤其是传递到javascript中,以制作图形.

I am struggling with a JSF project. In my service, I retrieve a List of custom object (here Sales), and I have to pass it to my jsf view, specifically into the javascript, to make graphs.

我的问题是,我不了解如何将数据从控制器(我的托管bean)发送到我的视图,以及如何在我的视图中使用哪个标签在我的JavaScript中进行检索.

My problem is, I don't understand how to send the data from the controller (my managed beans) to my view, and which tag to use in my view to retrieve it in my javascript.

我认为我可以像这样传递数据,但我不确定

I think I can pass my data like this, but I'm not sure

public String passData() {
    List<Sales> bestSelling = saleService.getBestSellingProduct(null, null, null, null);
    List<Sales> worstSelling = saleService.getWorstSellingProduct(null, null, null, null);

    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("bestSelling", bestSelling);
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("worstSelling", worstSelling);

    return "./all.jsf?faces-redirect=true";
}

推荐答案

您需要创建一个分配给JavaScript变量的JSON对象.要创建JSON,您可能会发现合并诸如 Gson 之类的库很有用.

You need to create a JSON object that you'll assign to a JavaScript variable. To create JSON you may find useful to incorporate a library like Gson.

所以,它看起来像:

var sales = #{bean.jsonList};

Bean#getJsonList为:

public String getJsonList() {
     return (sales == null) ? "" : new Gson.toJson(sales);
}

请不要忘记,具有这样的赋值的脚本必须由FacesServlet 处理.

Just don't forget that the script with such assignment must be handled by the FacesServlet.

这篇关于如何在JSF中将列表传递给javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆