I am attempting to retrieve JSON data in JavaScript but am seeing a null response in the action class

Having an issue with JSON data being sent through AJAX from the client side. The data is showing as null inside my action class.

Here is the JSON string:

{"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":2,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":3,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":4,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":6,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":5,"size_x":1,"size_y":1}
        ]
}

AJAX setup:

var seats = {"data" : positions};

    var seatPosition = JSON.stringify(seats);

    console.log(seatPosition);  

    $.ajax({
        url: 'retrieve-seat',
        data: seatPosition,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        async: true,
        success: function (data) {
        alert("success");

Configuring in struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

<constant name="struts.devMode" value="true" />
<constant name="struts.action.extension" value="," />
<constant name="struts.enable.SlashesInActionNames" value="true" />
<constant name="struts.custom.i18n.resources" value="global" />

<package name="default" namespace="/"
    extends="json-default,struts-default">

    <action name="retrieve-seat" class="com.pointwest.apex.actions.ReadPositionAction">
        <result name="SUCCESS" type="json"/>
    </action>

</package>

</struts>

Action class implementation:

public class ReadPositionAction extends ActionSupport {

private List<Seat> data;


public List<Seat> getData() {
     System.out.println("Getter Call");
    return data;
}

public void setData(List<Seat> data) {
     System.out.println("Setter Call");
    this.data = data;
}

@Override
public String execute() {
    System.out.println("action");
    try {
        System.out.println(data);


        System.out.println("Execute Method");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "SUCCESS";
}

}

The JSON format appears to be correct based on the console log. Any assistance would be greatly appreciated. Thank you!

Answer №1

If you are looking to generate JSON (Action -> JSP), simply use the json result.

If you need to parse JSON data (JSP -> Action), incorporating the Json Interceptor into your stack is essential.

According to the provided documentation:

Accepting JSON

Your actions can receive incoming JSON when they belong to a package that employs the json interceptor, or by adding a reference to it like this:

@InterceptorRef(value="json")

It's important to remember that the json-default package internally extends the struts-default, eliminating the need to extend both separately.

The configuration should look like this:

<package name="default" namespace="/" extends="json-default">

    <interceptor-stack name="jsonFromJspStack">
        <interceptor-ref name="defaultStack"/>
        <interceptor-ref name="json" />
    </interceptor-stack>


    <action name="retrieve-seat" class="com.pointwest.apex.actions.ReadPositionAction">
        <interceptor-ref name="jsonFromJspStack"/>
        <result name="SUCCESS" type="json"/>
    </action>

</package>

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

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

Guide on how to use JavaScript to swipe through loaded epub files in both lateral directions

Hello everyone, I have a question about implementing swipe functionality on a loaded epub using JavaScript. I successfully loaded the epub into a div and now I need to enable swipe left and right gestures on that div. I found a jQuery script that should a ...

Tips for sending a POST request with JSON data through the Google API client library in Java

Struggling to make a successful post request using the google api client library. This is the current snippet being utilized UrlEncodedContent urlEncodedContent = new UrlEncodedContent(paramMap); //paramMap consists of email and password keypairs HttpR ...

GULP showing an error message "ACCESS DENIED"

Exploring the fascinating realm of Gulp for the first time has been quite an adventure. I have managed to create a gulpfile that effectively handles tasks like reading, writing, and compiling sass/css/js/html files. However, when I try to access the site o ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Tap on the child to reveal their parent

I am working with a family tree that includes dropdown menus containing the names of parents and children. Each child has a link, and when I click on a child's link, I want their father to be displayed in the dropdown menu as the selected option. Can ...

Finding the commit ID through a Gerrit SSH query

I'm attempting to retrieve and store the commit ID for a specific gerrit commit. This command effectively provides all the information about the commit: ssh -p <port-num> <host> gerrit query --current-patch-set <change-id> This com ...

The update functionality of the p:commandButton seems to be malfunctioning when used within a ui:include

Looking to refresh part of a page using PPR (Partial Page Rendering). This section of the page needs updating: <h:panelGroup id="aggiungiAuto" rendered="#{!autoBean.operazioneOk}"> <ui:include src="../component/aggiungi_ ...

Is there a way to verify if the JSON Object array contains a specific value or not?

Hi there! I'm new to JavaScript and I have a question. I need to determine whether the value of an Object is included in a JSON file or not. If it is, then I need to do one thing, otherwise I need to do something else. First, I am retrieving the JSON ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Is there a way to improve or simplify this jQuery validation code?

I am implementing client side validation using jQuery to ensure all fields are filled in before proceeding. var passedValidation = new Boolean(true); // Validate Required Fields if ($('#fbsignup input.firstName').val().trim() == '') { ...

Modify button behavior on click after the initial press

Struggling to make this work the way I want. I have a button that should execute Javascript function A when clicked, and in function A, I need to change the onclick attribute to function B. This way, on the second tap of the button, it will trigger functio ...

Sustain information across two pages using Next.js

Recently, I have been considering reorganizing my Next.js webapp to allocate different pages for handling various screens. Currently, I have a component that manages multiple states to determine the screen being displayed. Within the jsx section, I utilize ...

Generating a .png image using the data received from the client [node]

I need to create a highchart client-side and save a PNG of that chart server-side. After successfully generating the highchart and converting it to a PNG using the following function: function saveThumbnail(graph_name, chart) { canvg(document.getEleme ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

Display the variable value in an HTML format following the submission of a request to an API using NODE JS, express, and jquery

Seeking assistance with completing a straightforward task: Creating an HTML AJAX link that triggers a Node.js API call to retrieve a value, wait for the response, and then display the value in HTML, JS, or PHP. After clicking on the "Get My Value" link be ...

Dealing with nested JSON structures in Python

I'm currently working on extracting data from a nested JSON structure using Python. Here's a brief example of the JSON data: { "daily" : { "1524182400000" : 438, "1524268800000" : 438, "1524355200000" : 437, ...

Ways to display JSON objects containing nested key-value pairs

In my JSON structure, each Mealplan includes a key and a corresponding value which is an object called meal. id: 1, mealsPerWeek: { Monday: { id: 4, name: "Burger", }, Tuesday: { id: 3, name: "Salad&qu ...

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...