methods for obtaining access in JavaScript when dealing with an ArrayList<Object> that has been converted to a JSONArray

I am dealing with an Object ArrayList that contains various variables, stored in an ArrayList of Objects. I then convert it to a JSONArray and pass it to a JSP page. How can I display these objects in a textarea on the JSP page using JavaScript?

public class myObject{
    private String fileName;
    private String filePath;
    private List<String> messages;

    //Constructor, empty constructor and accessor methods.

}

In my Java Controller,

ArrayList<myObject> filesContainer = //obtained from a source file
JSONArray jsFileList = new JSONArray(fileSources);

ModelAndView mnv = new ModelAndView();
mnv.addObject("fileList", jsFileList);
mnv.setViewName("forward:Test.jsp");
return mnv;

In my JSP page, I have created a text area:

<textarea rows="10" cols="50" id="display"></textarea>

<script>
    function fileList(){
        <% JSONArray fileList;
        if(request.getAttribute("fileList") != null){
            fileList = (JSONArray) request.getAttribute("fileList"); 

            %>


        <% } %> 
    }
</script>

How would I go about accessing the fileName and filePath in my JSP file?

Answer №1

Give this a shot:

for( int i = 0 ; i < fileList.length() ; i++ ){
    JSONObject file = fileList.getJSONObject("test");
    System.out.println(file.getString("fileName"));
    System.out.println(file.getString("ms"));
}

Check out:

Answer №2

Here is the method I use to fetch the data. Much appreciated for sharing...

var x = "<%= j.getString("fileName") %>";

function retrieveFiles(){
        <% JSONArray fileList;
        if(request.getAttribute("fileList") != null){
            fileList = (JSONArray) request.getAttribute("fileList");%>

            <%
                for(int i=0;i<fileList.length();i++){ %>

                <% JSONObject j = fileList.getJSONObject(i); %>
                var x = "<%= j.getString("fileName") %>";
                document.getElementById("fileSelector").value += x + "\n";

            <% } %>


        <% } %> 
    }

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

The style of the button label does not persist when onChange occurs

Encountered an interesting issue here. There is a button designed for selection purposes, similar to a select item. Here's the code snippet: <button class="btn btn-primary dropdown-toggle" style="width: 166%;" type="button" id="dropdownMe ...

AngularJS application: the button requires two clicks to activate

In my attempt to develop a simple CRUD app using AngularJS, I encountered an issue. The initial step involves clicking a button that fetches data from a REST API and populates an array. This array is then iterated using ng-repeat to generate Bootstrap card ...

Populate a Dropdown Menu with Directory Content for User Selection of d3.js JSON Data

I have a d3 forced-directed graph that is currently using a static JSON file for data: d3.json("../Data/sample.json", function(error, graph) { //do stuff }); However, I would like to give the user the ability to select the data file from a drop-down ...

Exploring the PHP array slice feature

Hey there, I'm currently facing a challenge with iterating through my array chunks. I am working on creating an image gallery where groups of three images follow a specific pattern and then the next set of three follows the opposite pattern. I believ ...

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

New Ways to Style the Final Element in a PHP Array - Part 2

So, here's the current challenge I'm facing along with a detailed explanation of what I'm trying to achieve. Initially, following your suggestions worked smoothly; however, things took a drastic turn when I altered the ORDER BY field and int ...

In my Node.js/Express.js application, I have a directory that holds various images. Whenever I attempt to view these images via their URL, I encounter a 404 error message

In my Node.js/Express js project, I have the following folder structure: root ----bin ----controllers ----middleware ----models ----node_modules ----public --------images ------------test.png ----routes ----views I am currently trying to determine the cor ...

Is it possible to configure npm install to install "bin" executables directly into the local node_modules directory (rather than the .bin directory)?

In my Node project, I am able to package it into a tarball using npm pack, and then install it in another directory for testing purposes. This allows the files specified in the "bin" section of my package.json file to be symlinked correctly into the node_m ...

The act of sorting an item in jQuery triggers a reordering of items

I am working with a collection of items that represent different layers within div elements. One of my goals is to ensure that when I rearrange these items, their corresponding div layers are also sorted accordingly. Here is the list of sortable items: & ...

The React syntax is malfunctioning

componentDidMount() { const restaurants = Restaurant.all() restaurants.then( rests => { this.setState({ restaurants: rests }) }) } render() { const { restauran ...

Utilizing Mongoose Schema Enums Alongside TypeScript Enums

In our Typescript-based NodeJs project utilizing Mongoose, we are seeking the right approach to define an enum field on a Mongoose schema that aligns with a Typescript enum. To illustrate, consider the following enum: enum StatusType { Approved = 1, ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

Unleashing the Power of Python for Unraveling Insights from

I've been given a task to use Python for extracting data from a JSON file. The JSON file I have looks like the following: {"votes": {"funny": 15, "useful": 48, "cool": 18}, "user_id": "JkeCKyEaQlbLd9uZYl4DjA", "name": "LiiLii C.", "url": "http://www. ...

What are the benefits of keeping JavaScript and HTML separate in web development?

Recently, I came across the concept of Unobtrusive JavaScript while researching best practices in the realm of JavaScript. One particular point that grabbed my attention was the idea of separating functionality (the "behavior layer") from a web page's ...

The resizing function on the droppable element is malfunctioning on Mozilla browsers

I've been working on making one div both droppable and resizable. Surprisingly, everything is functioning perfectly in Chrome but not in Firefox. If you'd like to see the issue for yourself, here is my jsFiddle demo that you can open in Firefox: ...

Using JOLT, perform an inner join between two arrays based on the matching IDs of their objects. Here is an example scenario for clarification:

I am looking to merge two arrays based on objects that share the same id (example below) { "body": { "array1": [ { "id": "13910", "name": "A" } ], "a ...

The URL overwrites the Ajax transfer type

When making an ajax call using a generated URL from a paginator script, I encountered an issue. The URL was dynamically created as shown below: "http://192.168.1.23:8000/pricing/0/999/null/?page=9" A similar link is generated on the server: "https://xxx ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

Is there a method to transmit data without escaping it in JavaScriptSerializer?

Recently, I created a custom .ToJson() extension method like this: public static string ToJson(this object obj) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(obj); } This handy method allows me to eas ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...