Transmit information from a bean to JavaScript using JSON in JavaServer Faces

I need help transferring my arraylist from a managedBean to JavaScript code.

The bean code is shown below:

public void getDataAsJson(){
    String [] dizi={"Tokyo","Jakarta","New York","Seoul",
              "Manila","Mumbai","Sao Paulo","Mexico City",
              "Dehli","Osaka","Cairo","Kolkata",
              "Los Angeles","Shanghai","Moscow","Beijing",
              "Buenos Aires","Guangzhou","Shenzhen","Istanbul"};

    Random rnd =new Random();

    JSONObject obj= new JSONObject();
    for (int i = 0; i < dizi.length; i++) 
        obj.put(dizi[i], new Integer(rnd.nextInt(80)));
}

The JavaScript code in the xhtml page looks like this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
<!--

$(function () {

    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                zoomType: 'xy'
            },
            title: {
                text: 'Average'
            },
            subtitle: {
                text: ''
            },
            xAxis: [{
                gridLineWidth: 0.5,
                categories: [// here is my city names which come from mybean]
            }],
            yAxis: [{ // Primary yAxis
                labels: {
                    formatter: function() {
                        return this.value;
                    },
                    style: {
                        color: '#89A54E'
                    }
                },
                title: {
                    text: 'Average',
                    style: {
                        color: '#89A54E'
                    }
                }
            }],

            series: [{
                name: 'Average',
                color: '#89A54E',
                type: 'spline',
                data: [// // here is my city's average which come from mybean],
                       labels: {
                        rotation: -90,
                        align: 'right',
                        style: {
                            fontSize: '13px',
                            fontFamily: 'Verdana, sans-serif'
                        }
                    }
            }]
        });
    });
});
//-->
</script>

This is how the body in the xhtml page is structured:

<body>   
  <script src="http://code.highcharts.com/highcharts.js"></script>
  <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body> 

Answer №1

JSF should be viewed as a tool for generating HTML/JS code specifically in this scenario.

All you have to do is allow JSF to output the data you want in a way that conforms to valid JS syntax.

categories: #{bean.dataAsJson}

The method getDataAsJson() will return a String containing the desired JSON code. For example:

public String getDataAsJson() {
    return "['foo', 'bar', 'baz']";
}

To confirm the outcome, simply right-click on the page in your browser and select View Source.

categories: ['foo', 'bar', 'baz']

Answer №2

Transferring data to a JavaScript routine through a JSF Bean may not be the best approach, but my solution involves utilizing a Java web service or JAX-RS. The Java web service consists of two classes: JaxRsActivator and a resources class. Here is the source code for JaxRsActivator:

package service;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}

And here is the source code for the resource class:

package service;

import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/resource")
@Produces(TEXT_PLAIN)
public class Resource {

    @GET
    @Path("cities")
    public String getCities() {
        String cities = "{\"Tokyo\",\"Jakarta\",\"New York\",\"Seoul\",\r\n" + 
            "\"Manila\",\"Mumbai\",\"Sao Paulo\",\"Mexico City\",\r\n" + 
            "\"Dehli\",\"Osaka\",\"Cairo\",\"Kolkata\",\r\n" + 
            "\"Los Angeles\",\"Shanghai\",\"Moscow\",\"Beijing\",\r\n" + 
            "\"Buenos Aires\",\"Guangzhou\",\"Shenzhen\",\"Istanbul\"};\r\n";
        return cities;
    }

}

Next, let's make a modification in our JavaScript. Transform your anonymous function for generating a chart into a named function such as generateChart(CityData) and update the line with data: to become data: CityData, The JavaScript should start like this:

$(function () {
    var xhr = new XMLHttpRequest();
    // replace the dots
    var url = "http://localhost:8080/........../resource/cities";           

    xhr.onreadystatechange = function() {
    // Check if fetch request is done
     if (xhr.readyState == 4 && xhr.status == 200) { 
        console.log(xhr.responseText);
        // Parse the JSON string
        var jsonData = eval(xhr.responseText);
        generateChart(jsonData);
        }
    };

    // Perform the HTTP call using the specified url variable above
    xhr.open("GET", url, true);
    xhr.send();

    function generateChart(CityData) {
        // Implement your code for generating the chart
        // Update the line
        data: CityData
    }

// End of JavaScript

Also include this JavaScript at the end of your JSF page. Initiate the JavaScript with data loading after the page loads, followed by generating the chart after the data is loaded.

Success.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Limiting the display to only a portion of the document in Monaco Editor

Is there a way to display only a specific portion of a document, or in the case of Monaco, a model, while still maintaining intellisense for the entire document? I am looking to enable users to edit only certain sections of a document, yet still have acce ...

Trouble with triggering events from Datatable buttons

Below is the code snippet I am currently using for my DataTable : var oTable12= $('#example').DataTable({ "aaData": tableData, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 5, "aoColumnDefs ...

Traverse through an object in ReactJS

Having trouble iterating over an object in my ReactJS project and facing some content display issues. Check out this fiddle for reference - http://jsfiddle.net/8e039Ltw/ Here's the ReactJS code snippet:- class TodoApp extends React.Component { ...

What is the best way to integrate JavaScript with my HTML command box?

I'm having some trouble with an HTML command box that is supposed to execute commands like changing stylesheets and other tasks. I thought I had everything set up correctly, but it doesn't seem to be working at all. Below is the HTML code with th ...

Create a dynamic form using JSON data and the Material UI library

Looking for assistance in creating a dynamic form on Next.js by parsing JSON files and generating the required components from the JSON data. Additionally, seeking guidance on utilizing the Material UI library for styling. Any examples or help would be g ...

Utilizing JSON for configuration settings in a C# program

Is it possible to set or unset configuration options for a C# software application using JSON within the GUI? Thank you ...

How can you make an Angular directive activate only after the scope function in an ng-click handler has been executed?

Scenario I am relatively new to Angular and facing a specific challenge. The goal is to make a directive change the color and add an image to a button. However, I am struggling to get the first if condition to work in my Angular Directive. Issue The ob ...

Is it possible to leverage both functions and variables within the ng-options expression in Angularjs?

I am faced with a situation where I have 2 select boxes. The first one is used to choose the user type (such as groups or individual), and the second one displays the options based on the selection made in the first box. I was wondering if it is possible t ...

Adjust the height in proportion to the width

My goal is to adjust the height of the li's based on their width using JQuery. var width = $('li').width(); $('li').css('height', width + 'px'); However, I've encountered an issue as it doesn't resu ...

How can I store the input from dynamically generated textboxes in Flutter?

Here is my complete code. To run it successfully, all you need to do is add "http: any" to dependencies in the pubspec.yaml file. The purpose of this code is to fetch JSON input from a source and create a card for each entry in the JSON feed. I want users ...

Make sure to validate a form when submitting from an external source rather than through an HTML

In my form, there are various input fields (some acting as inputs even if they're not). Each field is validated upon submission by angular validation and html attributes like required, ng-maxlength, minlength, etc. Now, we want to implement a keyboar ...

"Is there a way to extract a specific value from an XML file based on another element

<dataset> <study recNO="0" seriesRecCount="1"> <patientID>123456</patientID> <accessionNumber>M120170428105320</accessionNumber> <patientIDID>35</patientIDID> <studyUID>2.25.1439 ...

make the chosen text appear on Internet Explorer

1 How to insert text into a text box using code? 2 Moving the caret to the end of the text. 3 Ensuring the caret is visible by scrolling the text box content. 4 Programmatically selecting specific text in a textbox. 5 **How to make selected text visible?** ...

Ways to style a div element in CSS to achieve a unique shape

Hello there! I'm looking to achieve a tilted background div effect. Anyone have any tips or ideas on how I can do this? I'm new to web development and would appreciate the guidance. https://i.stack.imgur.com/wyj1X.png ...

How to reference a variable name within a JSON selector in AngularJS

I am working on a table using angularjs where I need to iterate through an array to display specific headers from a json object. The header displays correctly, but the issue arises when trying to utilize a variable from my nested ng-repeat as a json select ...

choose checkbox option in python

Suppose you have an XML document structured as follows: <!-- Location --> <w:t>Location:</w:t> <w:t>Home:</w:t> <w:t>Extension:</w:t> <w:t>Hajvali –Prishtina</w:t> <w:t>Street. "Martyrs of Goll ...

The complete guide to effectively concealing double arrows within a Bootstrap 4 custom-select component

If you're looking to hide the double arrow on the right of the bootstrap 4 custom-select field, there have been solutions provided here. However, even after implementing those changes, the text on the right-hand side still gets obscured by the opaque ...

A guide on demonstrating time using the AngularJS date filter

Is it possible to display the time in AM and PM using the angular date filter? I attempted to achieve this with the provided code, however, it did not yield the desired result. <div>{{ '12:31:07' | date:'HH:mm' }}</div> ...

In angular, concealing the pagination bar can be achieved when the quantity of pages is lower than the items per page count. Let's delve into

I am facing an issue where I need to hide the pagination bar if the number of pages being rendered is less than the items per page. I attempted to use ng-show but it was not successful. <tr ng-repeat="row in allItems"> ...

jQuery fails to hide DIVs when jQuery.show() has been utilized in a previous event

I've always considered myself pretty proficient in jQuery, but this particular issue has me stumped. Essentially, I have a click event that should hide one DIV (a placeholder) and show two others (an input section and control buttons section). However ...