What is the preferred method for transferring server-side data to JavaScript: Using Scriplets or making an AJAX call?

At the server side, there is a property file that contains a list of words separated by commas.

words.for.js=some,comma,separated,words

The goal is to convert these words into a JavaScript array.

var words = [some,comma,separated,words];

There are two approaches that I have considered:

1. Using a JSP scriptlet to create a global variable

<%  
    out.print("<script> var words = [");
    out.print( PropertyLoader.getAsCommaSeparated("words.for.js") );
    out.print(" ] </script>");
%>

2. Implementing a service/action (e.g., /getWords.do) and using AJAX to make a call in order to construct the array.

I am uncertain which approach is superior and would appreciate your insights. Is there perhaps a better way to achieve this task?

Thank you.

EDIT:

This also involves comparing a global JS variable (option 1) with an additional HTTP request (option 2) - which one is less optimal? Your perspective on this comparison would be valuable as well.

Answer №1

Personally, I find it more efficient to include server-side data directly within your JSP's code - #1. This method is quicker and eliminates the need for a callback.

When considering the type of data being used, embedding it in the markup seems suitable for static data like that stored in a properties file. In this scenario, avoiding an extra network request by including it as a global variable makes sense.

However, if you are working with dynamic data, utilizing an ajax callback onload would be the better option.

Answer №2

Utilizing an http request for exposure would present a graceful solution with the added benefit of allowing refreshes. The reliance on the browser's javascript capability is already assumed.

Furthermore, if the data is static, consider serving it as a standalone javascript file containing the array initially instead.

Answer №3

Have you considered utilizing JSON for sending data to the front end? It can be a more efficient way to handle string data. Here is an example:

String[] s = {"test","test1"};
JSONArray array = new JSONArray();
array.put(s);
request.setAttribute("test", array);

In your JSP file, you can access the array like this:

<script>
  var array='${test}'
</script>

Update:

It's recommended to store configurations in the servlet context as it remains consistent throughout the web application and doesn't change unless the application is restarted.

ServletContext context = getServletContext();
Properties prop = new Properties();
prop.load(context.getResourceAsStream("/WEB-INF/filename.properties"));
String[] configArray = prop.get("words.for.js").toString().split(",");
context.setAttribute("configArray", myConfigArray);

If you are using ServletContextListener, you can set the configuration array like this:

ServletContext ctx = servletContextEvent.getServletContext();
ctx.setAttribute("configArray", myConfigArray);

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

Using Lodash to Substitute a Value in an Array of Objects

Looking to update the values in an array of objects, specifically the created_at field with months like 'jan', 'Feb', etc.? One way is to loop through using map as demonstrated below. However, I'm curious if there's a more co ...

react-intersection-observer is specifically designed to function with the final elements

I am currently working on implementing the Lazy Loading feature using react-intersection-observer. The main objective is to load images in the boxes only when they appear within the viewport. At the moment, as I scroll down to the last elements, all the i ...

Sending user input data to a function in a React component

I am currently facing a challenge where I must retrieve the value of an input field in order to initiate an API request. Here is my current setup: import React, { Component } from 'react' import axios from 'axios'; const fetchWeather ...

Issue with moveByOffset() function in Selenium

Encountering an issue with the moveByOffset() method. Having trouble moving a slider back to the left side after moving it to the right using this link. Could there be a problem with the moveByOffset() method or is there another method I should consider? ...

Tips for updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

The POST request functions smoothly in Postman, however, encounters an error when executed in node.js

Just recently I began learning about node.js and attempted to send a post request to an external server, specifically Oracle Commmerce Cloud, in order to export some data. Check out this screenshot of the request body from Postman: View Request Body In Pos ...

JSF not triggering Ajax event

I'm facing an issue where the Ajax event is not firing to call the actionListener or update the second select menu. Can anyone help me with what might be causing this problem? <p:selectOneMenu value="#{player}" converter="playerCon ...

Finding the substring enclosed by two symbols using Javascript

I'm working with a string that contains specific symbols and I need to extract the text between them. Here is an example: http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_se ...

Mastering the process of running selenium automation scripts (written in Java) with Safari Technology Preview

Seeking assistance with running automation scripts on Safari. Currently utilizing Selenium Webdriver scripts on Mac OS (High Sierra) and Safari 11.1.2 I've added the WebDriver Extension to the Safari browser and enabled 'Allow Remote Automation ...

Combining multiple storageStates in a playwright context for efficient loading

I am trying to load multiple storageStates into a single context in playwright, but I am facing some issues. When using the following code: const context = await browser.newContext({ storageState: "telegram.json",storageState: "google. ...

Using `href="#"` may not function as expected when it is generated by a PHP AJAX function

I am facing an issue with loading html content into a div after the page has loaded using an ajax call. The setup involves a php function fetching data from the database and echoing it as html code to be placed inside the specified div. Here is my current ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

Unable to eliminate user registration feature with Meteor and React

Exploring the world of Meteor and diving deep into its functionalities, I am currently focused on creating a user login and signup page with personalized control panels for each registered user. Although I have successfully implemented the signup and logi ...

Unable to parse List<Serializable> using Gson

I am facing an issue with deserializing a JSON received from the server back into its original POJO form. Despite having access to the source code of the server, I seem to be encountering a roadblock. Below is a concise code snippet that highlights my pro ...

The performance of HTTP requests is significantly decreased in Internet Explorer compared to expected speeds

I am currently developing an Angular site where I need to send a significant amount of data (approximately 1 MB) in an API call. In the Chrome and Firefox browsers, everything works smoothly and quickly, with a response time under one second. However, whe ...

When a barcode scanner is used, it will trigger a "keypress" event only if the user is currently focused on an input box. Is there a specific event to monitor when the user is not on an input

Scenario: In the development of my web application, I am utilizing a barcode scanner device that allows users to scan barcodes for navigation to specific pages. Challenge: The current barcode scanning device is set up to only trigger "keypress" events w ...

Tips for identifying when a tab has been reopened following closure?

There seems to be a problem with the JS state where it changes but then reverts back to its original state when the tab is closed and restored using cmd/ctrl + shift + t. Typically, data is fetched from the server via ajax using Vue's mounted() lifec ...

Update the fuelux treeview after uploading a file

Currently, I am utilizing the jquery fileupload plugin to facilitate the process of uploading a file and then using the data from said file to populate a fuelux treeview. I have configured an ajax call for handling the file data where the information is fe ...

forward to a different link following the backend script execution

I am facing a challenge with the signup.php page which includes a Facebook login button. The structure of the page is as follows: <?php if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- ...

Establish a connection using node.js to enable communication between a server and a client

Running a node.js Server:- // *********** Setting up a server to receive orders ************ // // requiring the http module. // var http = require('http'); // initializing request variable as an empty string. // var req = ""; // creating th ...