Obtaining a JSON Java object with JavaScript: Step-by-step guide

I have a requirement to store key-value pairs in a JSON object. I've actually managed to do this on a Java class, as shown below. However, I'm struggling with how to access that same JSON object in the Java Script on my JSP page. Can someone please assist me with this issue?


import org.json.simple.JSONObject;
class BeanManager{
    private JSONObject jsonObject;
    public JSONObject getJson()
    {
        jsonObject=new JSONObject();
        jsonObject.put("name","Jack Daniel");
        jsonObject.put("age","3");
    }
}

Answer №1

Embedding JSON data into an HTML element in JSP, then parsing and evaluating it as a JavaScript object can be a quick fix, but may not be the most sustainable solution.

It is advisable to explore alternative methods for better long-term performance.

Answer №2

Before directing to your JSP, make sure to attach your class instance as a request attribute and then utilize it in the view afterwards. Additionally, avoid performing business logic within the getter method (and ensure you are returning an object when necessary).

Overall, the structure of the class code could be similar to:

class BeanManager{

private JSONObject jsonObject;
private String jsonObjectString;

public BeanManager() {
    jsonObject=new JSONObject();
    jsonObject.put("name","jack Daniel");
    jsonObject.put("age","3");
    jsonObjectString = jsonObject.toString();
}

public JSONObject getJsonObjectString() {
    return jsonObjectString;
}

}

The corresponding servlet section may resemble:

BeanManager bm = new BeanManager();//customize it accordingly
request.setAttribute("bean", bm);
request.getRequestDispatcher("/WEB-INF/view.jsp").forward(request, response);

The view could include the following segment:

<script>
    var json = ${bm.jsonObjectString};
</script>

By doing this, the JSON variable can be accessed within the JavaScript environment.

If you are looking to handle AJAX requests, refer to How to use Servlets and Ajax? question and its solution. In that scenario, a JSON object is sent back from the servlet and subsequently converted into an HTML document.

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

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Tips for efficiently sharing or waiting for data between files in Mocha

Imagine having a file called "main.js". It includes the following: const User = require('../models/user'); describe('Testing', () => { before(async function(){ await User.deleteMany({}); }); require('./users ...

Guide on determining the quantity of elements in a JSON array using Groovy scripting language

Looking for assistance with determining the size of an array in a JSON file called "sample.json". Here is the content of the sample JSON: {"apps": ["app1", "app3", "app3"]} I attempted to get the array size using th ...

What are the latest advancements in using Java for AJAX technology?

Interested in creating a Rich Internet Application (RIA) with AJAX using Java for the backend. Although DWR may offer an RPC style approach, it hasn't been updated since 2008. Considering alternatives like DOJO and GWT as well. Seeking recommendati ...

A guide on parsing ndjson in Pharo using NeoJSON

I am exploring the process of parsing ndjson (newline delimited json) data using NeoJSON on Pharo Smalltalk. An example of ndjson data is shown below: {"smalltalk": "cool"} {"pharo": "cooler"} Currently, I am converting my file stream to a string, split ...

What is the reasoning behind websites predominantly opting for new windows for authentication as opposed to using pop-up dialogs or iframes?

In developing a widget that prompts for authentication when clicked on a third-party site, I've noticed that most websites use pop-up windows for this process instead of in-page dialog boxes like inserted iframes. I'm curious about the security i ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

The request in Node.js was terminated

While using express and body-parser to transfer a large amount of data from one server to another, I encountered the following exception after some time: { "message": "request aborted", "code": "ECONNABORTED", "expected": 99010, "length": ...

Java Selenium: Troubleshooting Problem with Dropdown Selection

I am encountering an issue while trying to automate the checkout process, specifically with selecting a value from a dropdown in the cart. Here are the steps I am following: Search for the item and select it Choose the size and quantity Click on "Add to ...

What are the different elements that can be chosen on iOS?

The content within this non-editable div consists of text. How can I enable users to conveniently select specific portions of the content? UPDATE: The individual characters in the text are enclosed within separate span tags, making it more complex than st ...

Taking out the character from a sequence of characters

I am currently in the process of encrypting text using the Vigenere cipher. Typically, the key is required to be shorter than the original text. However, what if the key happens to be longer than the text itself? I could use some assistance in figuring out ...

Looking to identify the data type of the response parameters in Spring?

I am attempting to fetch a JSON response with parameter types for the frontend. For example: { "address": "String", "role": { "admin": 0, "user": 1, "company": 2 }, "level": "String", "surname": "String", " ...

Having issues executing a conditional check using ng-if in AngularJS

I am attempting to verify a condition and here is how it appears: <ons-list-item ng-repeat="EventList in EventLists" ng-if="EventList.start.dateTime | DateMonth == TodayDetail"> I am encountering difficulties with this ng-if="EventList.start.dateTi ...

Animating with React JS using JSON data sources

Currently, my project involves using React/Redux to store animation data in JSON and display it on a React page. The challenge lies in implementing the animations correctly while utilizing setTimeout for pauses and setInterval for movement. The Animation ...

Error in jQuery deferred: undefined property 'then' cannot be read

I am attempting to store the contents of an array in cache before utilizing it throughout my program. Using jQuery deferred objects, I believed I had a grasp on the concept, but it seems like there might be a missing piece. Please refer to the code snippet ...

Is there a way to collapse an element by clicking either the content inside the div or the button within the div?

Is there a way to make a button within a newly activated div close it? The existing code seems to have issues with this functionality, and adding new rules or functions has not solved the problem. Any assistance with fixing this issue using vanilla JavaScr ...

Comprehending the recursive process behind generating powersets

I stumbled upon a code snippet that generates powersets of an array. However, I am having trouble grasping the logic behind the subseq() method. Based on my understanding and observations while debugging - 1. An empty set is initially added. 2. Enters t ...

Issues with dynamically adding or removing scroll in jQuery are not being resolved

I am trying to implement a dynamic scrolling feature in my post scenario. The goal is to automatically add a vertical scroll when the number of dynamic inputs reaches a certain threshold. Specifically, if there are more than 5 dynamic inputs created, a ver ...

An essential React Native component that necessitates rnpm linking for proper functionality

I have just finished developing a new React-Native component that I plan on releasing as an npm package soon. However, I have encountered a problem. This component relies on another npm package called react-native-image-resizer, which needs to be linked w ...

The message sent back by Django Rest Framework is: "a legitimate integer must be provided"

I have integrated a react form within my Django application, supported by the rest framework in the backend. When I submit the form without entering any value in the integer field, I encounter the following error message from the rest API: "a valid integer ...