Binding parameters to a collection in Struts 2 without the need for indexes

Struts Version: 2.3.16.3

Is there a way to populate a list of objects without specifying the index? Currently, I am required to reference the collection in this manner:

<input name="myCollection[0].myProperty" value="some value" />

I wish to be able to achieve something like the following:

<input name="myCollection[].myProperty" value="some value" />

As I am dynamically adding and removing elements on the page using JavaScript, it has been challenging to correctly manage the indexing. It would be more convenient if the backend could simply add new elements to the end of the collection as they come across from the form, similar to how PHP handles it.

The documentation for the parameters interceptor suggests that the input name is binding to an OGNL expression. Upon checking the OGNL docs, I found that arrays can be referenced in this way:

array["length"]

This would indicate the next element in the array. However, when attempting this approach, the parameter interceptor indicates rejection of this parameter name. I am eager to discover a solution for this issue, even if it involves extending the parameters interceptor.

Answer №1

When you find yourself manipulating the page using Javascript and encountering difficulty in detecting or updating the index of elements when adding or removing them, a straightforward solution is to:

  1. Utilize the preferred syntax for manipulation, such as myCollection[].myProperty.
  2. Transform them into the desired format for Struts during a pre-submit action.

This approach eliminates the need to manage indexes while manipulating elements. Instead, you can loop through them by name at the end and adjust their names with JavaScript by assigning the correct index.

Here's a quick example using jQuery:

$(function() {
  $('#myform').submit(function() {
    $('[name^="myCollection[]"]').each(function(index) {
      var oldV = this.name;
      var newV = oldV.replace("myCollection[]", "myCollection[" + index + "]");
      console.log("was: " + oldV + " - now is: " + newV);
      this.name = newV;
    });
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform">
  Open Javascript Console, then press submit, then inspect input elements
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <input name="myCollection[].myProperty" />
  <br>
  <button>submit</button>
</form>

Answer №2

It is important to be able to identify which object a particular property belongs to, and indexes are commonly used for that purpose. It's not advisable to simply remove them without considering other methods.

There are multiple approaches you can take to achieve your desired outcome. Take a look at Andrea's answer for a potential solution using JavaScript.

Another option is to extract object properties into simple lists and then assign them back to the object.

For example:

private List<String> myProperty;

You can reference this in JSP without needing indexes:

<input name="myProperty" value="first value" />
<input name="myProperty" value="second value" />

However, if you have multiple properties, you will need to ensure they are synchronized in JSP so that the order and size of properties in the list remains consistent for each property.

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

Attempting to maintain the main navigation highlighted while browsing through the secondary navigation

I am facing a small issue that seems like it should be an easy fix, but I can't seem to figure it out. While working on my site, I'm having trouble keeping the parent navigation highlighted when scrolling through the sub-menu. If you hover over ...

Is the memory consumption higher for a subclass compared to a superclass?

When comparing an object initiated with class A to one initiated with class B, where class B inherits from class A, is there a difference in the amount of memory these objects occupy in the heap? Two scenarios to consider: Scenario 1: class A { String ...

Checking for file existence using the HEAD command can be done by specifying the file path as

I am seeking to utilize the Spring Endpoint provided below for file uploading. @PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<StringResponseDTO> uploadFile(@RequestParam("file") MultipartFi ...

How to take advantage of the onOk method in Vue Ant Design's Modal component

I am currently attempting to utilize Vue Ant's confirmation modal dialog, but I am encountering difficulties in accessing methods and data within the onOk prop. Whenever I try to call my methods or use this.$emit, I receive an error message stating "T ...

Switching styles in AngularJS without using ng-class

My goal is to allow users to switch the class from incomplete to complete when they click a button and the function(response) returns 1. I have attempted to use ng-class, but it is not effective because the HTML elements are generated with a PHP loop. This ...

How should FormData be structured?

After trying to upload the test JSON to arweave, I encountered an issue when attempting to append bufferTest. The error message displayed was: Unhandled Rejection (TypeError): Failed to execute 'append' on 'FormData': parameter 2 is not ...

When the email field is changed, the string is not being set to the state if it is

I encountered a strange issue while setting an email input as a string to state. Even though I can see on React Dev Tools that it gets sent, when I try to log it from another function, I get an empty string. The odd part is, if I change the order of the in ...

What is the best way to apply lodash's max function to a jQuery array?

I'm having trouble extracting the maximum number of rows from two tables. My variable maxRows ends up being a tbody jQuery element instead of the actual maximum value. I've experimented with both the pluck syntax and the long form, but both metho ...

Loading JavaScript on a different page using AJAX is not possible

Why is it that AJAX can load HTML, CSS, PHP, etc., but not JavaScript files when using JavaScript? Does AJAX have limitations in this regard? If so, how would one go about loading another HTML page that contains JavaScript with AJAX? Here's a simple ...

Transferring Information from a JavaScript Page to an HTML Page without the Use of a Form or URL

I am faced with a challenge in sending a variable from JavaScript to another HTML page and then redirecting to that page. The catch is that I cannot use forms because the first page consists purely of JavaScript and is stored as a .js file, thus ruling out ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

Activate the ng-change event when the selection option tag is fired

Here's an interesting question I have. Take a look at this jsfiddle http://jsfiddle.net/ctbLparv/ <select ng-model="bob" ng-click="test()"> <option value="5">5</option> <option value="10"& ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

Tips on how to lock a dropdown field to prevent editing while retaining the current value

Users on my website can input details about a car into a database and later edit this information on a separate "Edit" page. I want to prevent users from modifying the Make and Model of the car during editing while retaining the original values. I attempte ...

Retrieving a specific attribute pair from a JSON object

Currently, I am trying to retrieve the temperature data and display it on my webpage. Since these are objects with no specific order, I am struggling to understand how to access them without using an index. { "response": { "version": "0.1", "termsofServic ...

Pagination with composite queries in Firestore allows for efficient retrieval of

Currently I am attempting to paginate a composite index query, let size = data.length let lastElement = data[size-1].commentCount db.collection('user-content').orderBy('commentCount','desc').orderBy('likes', 'd ...

Switching Iframe Source with Javascript Button State

I'm currently working on creating a set of toggle buttons for a website that will change the content of an iframe depending on the combination of buttons selected. Let's say I want to display a product that is available in: - Three colors: Red, ...

Is it possible for me to interact with different elements upon hovering?

html, <div id="first"> <a>Click here</a> </div> <div id=second"> second div content </div> css, #first a:hover{ color:blue; /*change color on hover */ #second{ background:blue; } } In ...

Retrieve a Google map using Ajax in a PHP script

I'm attempting to display a google map on my homepage using the following function: function addressCode(id, concatenatedToShowInMap) { var geocoder; var map; geocoder = new google.maps.Geocoder(); ...

Locating an element using XPath in Java with Selenium

Hello everyone, this is my debut post on StackOverFlow. Please bear with me as English is not my first language! I am currently experimenting with Selenium for the following tasks: 1. Open the specified URL in the code. 2. Click on the "zonal" link under ...