What is the process for passing an Object from JavaScript to an Action class in Struts 2?

Within my Action class, there exists an object of the class that is a POJO.

public class ConfigureTspThresholdAction extends
    ActionSupport implements SessionAware, ModelDriven<GmaThresholdParameter>{

    private Map<String,Object> session;

    private String circleId;
    private String tspId;
    private String thresholdTypeFlag;

    GmaThresholdParameter gmaThresholdParameters = new GmaThresholdParameter();

The GmaThresholdParameter serves as the POJO (also known as my Entity class), containing various members with values intended to be filled by the user.

The data is retrieved from user input in textfields within my JSP:

JSP:

<s:div id="thresholdParametersDiv" cssStyle="display: none">
<table>
    <tr>
        <td>Minimum Number of OG Calls</td>
        <td><s:textfield id="thresholdParameter_1"
                name="minNumberOc"
                onkeypress="return isNumber(event,'thresholdParameter_1')"></s:textfield></td>
    </tr>
    <tr>
        <td>Minimum Duration of OG Calls (in secs)</td>
        <td><s:textfield id="thresholdParameter_2"
                name="minDurationOc"
                onkeypress="return isNumber(event,'thresholdParameter_2')"></s:textfield></td>
    </tr>
    <tr>
        <td>Maximum Number of IC Calls</td>
        <td><s:textfield id="thresholdParameter_3"
                name="maxNumberIc"
                onkeypress="return isNumber(event,'thresholdParameter_3')"></s:textfield></td>
    </tr>
    ..........and so forth for other textfields
</table>

The name attribute in these textfields refers to the member variables of GmaThresholdParameter, which need to be populated.

To capture and populate the values from these textfields into my

GmaThresholdParameter gmaThresholdParameters = new GmaThresholdParameter();
in my Action class.

While primitive variables are handled through getter/setters and sent in the AJAX call using matching names in the Action class like:

JS:

$.ajax({
    type: 'POST',
    traditional: true,                  
    url: '/gma/updateThresholdParameters.action',
    data:
    {
        circleId: circleId,
        tspId: tspId,
        thresholdTypeFlag: thresholdTypeFlag,

        // How can I send my GmaThreshholdParameter object here to fill the object in the action class?
    }

I am looking to transfer my GmaThreshholdParameter object from JavaScript to the Action class in order to update my object. What would be the best approach to achieve this?

Would it be feasible to gather values from textfields into an array for transmission or create a JavaScript Object that aligns with the Java POJO object? Is there a recommended solution for this scenario?

Answer №1

To extract values from text fields, you can simply create a data object in your code. By properly utilizing the ModelDriven interface and setting up the modelDriven interceptor as outlined in the official documentation, you won't have to provide a path to access nested properties as they are readily available on the valueStack's top layer.

data:
{
    circleId: circleId,
    tspId: tspId,
    thresholdTypeFlag: thresholdTypeFlag,

    minNumberOc: $("#thresholdParameter_1").val(),
    minDurationOc: $("#thresholdParameter_2").val(),
    maxNumberIc: $("#thresholdParameter_3").val()

}

Answer №2

To properly handle the gmaThresholdParameters in your Struts2 action, make sure to create both a getter and a setter.

Next, when working with JavaScript, consider using this approach:

...
data:
{
   circleId: circleId,
   tspId: tspId,
   thresholdTypeFlag: thresholdTypeFlag,
   "gmaThresholdParameters.property1": valueForProperty1,
   "gmaThresholdParameters.property2": valueForProperty2,
   "gmaThresholdParameters.property3": valueForProperty3, 
   ...
}
...

By ensuring that you have an empty constructor for the gmaThresholdParameters object along with appropriately defined getters and setters, it will be populated correctly.

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

Modify the color of the field that is currently chosen

Is there a way to modify the highlight color of the active record in an extjs combobox? In the image provided below, the record Petty Cash Fund is currently selected in my dropdown, but the highlighting is not very visible. How can I adjust this for all co ...

Verify the tags associated with an element that has multiple tags

For a test I am conducting, I need to examine the tags and styles present in a specific element. The element, displayed on the page as bold, italic, and centered, looks like this: <p style="text-align: center;"> <em> <strong>TE ...

Show information on a pop-up window using Ajax without having to open a new browser tab

I am currently working on a project that uses the Struts framework. In this project, I need to revamp the UI design. The existing project has a menu tab, and when each menu is clicked, a JSP page opens in a new browser window. However, I want these pages t ...

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Struggling to retrieve newly added elements from a HashMap?

Hey everyone I'm experiencing an issue that I can't figure out. I've added birthdays, but when I try to access them using getHashMap, I can't retrieve the elements in the swingmenu class. I have a theory about what's causing the pr ...

A guide on creating annotations and leveraging lombok alongside javapoet

Can Lombok be used with Javapoet for enhanced functionality? Consider the example below: TypeSpec typeSpec = TypeSpec .classBuilder("MyDtoWithLombok") .addModifiers(Modifier.PUBLIC) //.addAnnotation(NoArgsConstructor.cla ...

Building an Ajax request for Redux-Form operation to communicate with Mongo in a structured manner

I'm relatively new to working with JavaScript and React, and I've been using Redux-Form to add items to my MongoDB. The form is set up correctly and the API connection to the database is defined, but I'm struggling with structuring the actio ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Encountering an issue while trying to set up a fresh react application

Issue encountered when trying to start a new React project ...

execute javascript code after loading ajax content

Although this question may have been asked before, I am completely unfamiliar with the subject and unable to apply the existing answers. Despite following tutorials for every script on my page, I have encountered a problem. Specifically, I have a section w ...

Is there a way to add 100 headings to a webpage without using a loop when the page loads

Just joining this platform, so please be patient with me! The task at hand is to insert 100 h3 headings on page load ("Accusation 1, Accusation 2, Accusation 3,...Accusation 100"). We are restricted to using only 1 loop throughout the lab, which will also ...

Issues related to validation prior to submission

Having trouble with a VeeValidate example from the documentation. The example can be found here. I seem to be missing something crucial but can't figure out what it is. For some reason, my form always validates as valid, even when no text is entered ...

Do you mean using a JSON object as a value?

When creating a JSON object where the value itself is an object, what is the correct way to write it? var data ='{"phone":{"gtd": "080"}}'; OR var data ='{"phone":"{gtd: 080}"}'; This question may seem straightforward. I am curious ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

Loop through an array of objects, then store each one in MongoDB

If I receive an Array of Objects from a Facebook endpoint, how can I save each Object into my MongoDB? What is the best way to iterate over the returned Array and then store it in my mongoDB? :) The code snippet below shows how I fetch data from the Face ...

Extending a type by adding properties from separate files using TypeScript

I am faced with a situation where I have a file containing either a type or interface variable (all of which are exported), and I need to add new properties to this variable from different files without using extends. Essentially, making changes to the sam ...

Saving the current date in MongoDB using the save method

Is there a way to have MongoDB automatically populate a field with the current UTC DateTime when saving a document? I'm aware of the $currentDate operator, but it seems to only be accessible within the update method. ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...