【问题标题】:Write JSON to HTTP response in JSF在 JSF 中将 JSON 写入 HTTP 响应
【发布时间】:2015-09-22 14:37:51
【问题描述】:

我想在 JSF 中使用 de JavaScript 库“D3.js”创建动态图表。我的意思是动态地,Java 方法从数据库中获取数据并写入相应的 JSON。这个方法我已经编程了,它有效。然后 JavaScript 应该访问 JSON 并创建图表。

我的问题是:如何将 JSON 字符串/文件传递给 JavaScript。我认为最好的方法是把它写在 HTTP 响应中。但是如何在 JSF 中做到这一点?或者您有其他建议吗?

【问题讨论】:

  • 为什么要用'jsf'?什么不是简单的休息服务?
  • @Kukeltje 因为我用 java 编写 JSON。
  • jax-rs(java rest 服务实现)IS java... 请从开发中退后一步,学习一些有关您打算使用的技术的基础知识。见stackoverflow.com/questions/29982657/…

标签: javascript json jsf servlets httpresponse


【解决方案1】:

只要让 JSF 打印出 JSON 字符串,就好像它是一个 JS 变量一样。

<script>var data = #{bean.json};</script>

【讨论】:

  • 是的,比我的简单。
【解决方案2】:

一步一步:

  • 创建一个支持 bean 方法,用于使用数字数组字符串 JSON 表示更新字符串属性 (jsonData)。您必须:

    • 调用返回数据的 EJB bean 或 JAX-RS 服务。
    • 读取列表中的数据。
    • 将 List 集合转换为 JSON 对象,然后对其进行字符串化,例如使用标准中的 javax.json 包。
    • 更新 jsonData 模型属性。
  • 在 JSF 页面中,您必须包含一个绑定到 jsonData 属性的 outputLabel 组件。你可以用 CSS 隐藏它。

  • 在 JSF 页面中编写 Javascript 代码以将组件值放入 Javascript 变量中。您可以使用 jQuery 选择器或带有 getElementById 函数的纯 Javascript 来实现它。

  • 最后你使用了 D3 库中的 Javascript 变量。

注意:D3 库的使用已从here 复制。

JSF 页面中的代码类似于:

<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>   

【讨论】:

    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2018-07-08
    相关资源
    最近更新 更多