Passing an array from Javascript to a Spring Controller without relying on jQuery

I am struggling to successfully send an array from my JSP page to a Spring Controller. After populating my array with the necessary data in the JSP, I initiate an AJAX request:

var ajaxRequest;  

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequest.open('POST', 'saveRecompensas.action');

    ajaxRequest.send('array='+array);

Upon reaching the Controller:

@RequestMapping ("/proyecto/saveRecompensas")
public String saveRecompensas(@RequestParam ("array") String[] array, HttpSession session){
//public String saveRecompensas(){  
System.out.println(Method saveRecompensas called");

    return null;        
}

The presence of two method signatures is intriguing. When omitting the @RequestParam ("array") String[] array, the method executes as expected. However, when including the RequestParam, the method fails to execute.

Am I sending the array correctly from the JSP to the Controller? Any guidance would be greatly appreciated. Thank you.

Answer №1

It seems that your issue is related to data binding, specifically due to not adhering to the conventions of how data binding functions in Spring. Spring has a specific method for handling data binding, which involves converting a stream of data into objects and native data types in a language or binding the data from the stream into a series of objects. You can either let Spring handle this process for you or take matters into your own hands. Since you appear to prefer the do-it-yourself approach, I'll skip the automatic type conversion explanation and provide you with an alternative solution.

  1. Change "@RequestParam("array") String[] array" to "@RequestParam("array") String inputArray"
  2. In your method body, add "String[] array = inputArray.split(",")

There you have it - your array. However, your current method of passing parameters in JavaScript may lead to issues because you are not properly escaping strings using encodeURI(). This could result in problems when the input changes.

If you're interested in exploring more advanced data binding techniques or making your example function correctly, you'll need to encode it in a manner that Spring understands. This involves adjusting your JavaScript implementation. Spring will identify an array based on multiple occurrences of the parameter name in the parameter string. For instance,

To encode your array effectively:

ajaxRequest.send( array.reduce( function( prev, curr ) { 
   return prev + (prev.length > 0 ? "&" : "") + "array=" + encodeURI( curr ); 
}, "" ) );

Note that the encodeURI( curr ) function ensures that values within the array, such as spaces, do not disrupt the server call.

Furthermore, if you frequently encounter this scenario, you might want to consider utilizing JSON to transmit data, as it enables more intricate data structures on the server (e.g., Objects).

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

How does Rest stand out from RPC in the context of Spring Boot?

When developing Rest APIs, we typically adhere to the MVC pattern. However, there is sometimes confusion between Restful APIs and RPC. Some argue that a CRUD operation from Spring Boot does not constitute a true Rest API as it should be in Http format. T ...

Choosing the Following Date from the Datepicker using Selenium IDE

I need the selenium IDE test case to automatically select a date following the steps outlined below: Start by clicking on the departure date to open the datepicker Loop through the dates starting with the currently selected day until the next available d ...

Iterate through the list retrieved from the backend

I have a list coming from the backend that I need to iterate through and hide a button if any element in the list does not have a status of 6. feedback The response returned can vary in length, not always just one item like this example with 7 elements. ...

Utilizing ASP.Net Core version 3 to effortlessly send a POST request to the controller

I am having difficulty with my POST request to an ASP.NET Core 3 server because the number always seems to be 0. Is there something specific in ASP.NET Core 3 that I might be missing? Using the [FromBody] parameter has not resolved the issue. Even passing ...

Create a placeholder for the module function

Update: Providing more specific details. Our team has developed a Github API wrapper extension and we are looking to test different use cases for it. However, we prefer not to use the API wrapper extension directly during testing and instead want to stub ...

Is there a way to incorporate hyperlinks into the Application column of my v-data-table component?

When loading data table from the database, I have included links along with the names of the Applications. However, I only want to display the Application name and open the corresponding link when clicked. headers: [ { text: 'Name&a ...

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

The execution of a nested object's function that calls a JavaScript function encounters an error

Below is a simple example demonstrating the issue I am facing, which you can also view on JSFiddle here. While I understand why the issue is happening, I'm unsure of how to resolve it without altering the existing JS structure. The problem arises wh ...

Main navigation category as parent and secondary category as a child menu in WordPress

Hello there, I am looking to create a navigation menu with parent categories displayed horizontally and child categories as corresponding submenus. For example, The parent categories would be Apple, Orange, and Mango Under Apple, we would have apple1, ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...

Monitoring Logfile in Ruby On Rails 3.1

Within my Ruby on Rails application, I have a set of scripts that need to be executed. In order to ensure they are working properly, the application must display and track the content of logfiles generated by these scripts. To provide more context: I util ...

Ways to make a personalized item within an array using javascript

JSON: (The array within this.schedulerForm.get("schedularList").value contains the following array: const result = [{ formula_id:1, quantity1:10, quantity2:20, quantit ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...

Unable to alter the protocol option of the request object in SailsJS

Currently, I am utilizing a library that relies on the req.secure option to proceed without any errors. However, my application is deployed on Heroku and I have implemented custom middleware to check the "x-forwarded-proto" header and set req.secure as tru ...

Backbone and Laravel - Choose a squad and automatically create users for the selected team

I've recently started exploring backbone.js and have gone through Jeffery Way's tutorial on using Laravel and Backbone. As of now, I have a list of teams being displayed along with their ids fetched from the database. I have also set up an event ...

Solving the issue of "_c is not defined" error in Vue functional component

I've been experimenting with creating functional components in Vue using the render method. Here's an example of how I attempted to do this: import Vue from "vue" const { render, staticRenderFns } = Vue.compile(`<div>Hello World</div&g ...

What are the steps to successfully deploy a static website created with Next.js on Vercel?

Using the Next.js static site generator, I created a simple static site that I now want to deploy on Vercel. However, I keep encountering an error during the build process. While I have successfully deployed this site on other static hosting platforms befo ...

Does anyone have tips on how to upload images to MongoDB using React?

Currently, I am working on a project that requires an image upload feature for users. These images need to be stored in MongoDB so that they can be viewed by the user later on. Can anyone offer assistance with this? I have successfully configured my datab ...

The code within $(document).ready() isn't fully prepared

Feeling frustrated after spending hours searching and attempting to refactor one of my old modules on a rendered Mustache template. It's like diving into code chaos. <section id="slideShow"> <script id="slideShow-template" type="text/tem ...

The callback response in Node's exec function is behaving incorrectly

When I have a route handling a URL post request, I am running an exec on a bash command. Strangely, the console.log is working fine indicating that the bash command ends and the callback is triggered. However, for some reason, the response fails to send ...