Guide to outputting a JSON array in Struts 2

Below is the code for my Struts action:

@Action("/trylogin")
@ParentPackage("json-default")
@Result(type = "json", params = { "includeProperties", "msg, productsList" })
public class Login extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String utilisateur;
    private String motdepasse;
    private String msg;
    private ArrayList<Article> productsList = new ArrayList<Article>();

    @Autowired
    private Dao dao;

    public String execute() {

        if (dao.validCredentials(utilisateur, motdepasse)) {
            System.out.println("USER FOUND");
            productsList = dao.fetchProducts();
            msg = "success";
        } else {
            System.out.println("ERROR");
            msg = "error";
        }
        return ActionSupport.SUCCESS;
    }

public ArrayList<Article> getProductsList() {
    return productsList;
}

public String getMsg() {
    return msg;
}

Next is my ajax post :

$.post({
    url: "trylogin",                        
    data: {                                 
        utilisateur: name,
        motdepasse: password
    }       
}).done(function(data) {                
    console.log(data.productsList.length);
}).fail(function( jqXHR, textStatus ) {     
    console.log("Fail");
})

I am facing an issue with fetching my productsList. Even though it is loaded properly in my Action, when I try to access data.productsList in JavaScript, it appears to be empty.

Can anyone guide me on how to successfully retrieve the productsList from my struts action to my javascript?

The productsList contains objects with attributes like name, id, color, etc.

Answer №1

The includeProperties parameter consists of a list of regex expressions. When utilizing the productsList parameter, the json serializer recognizes this property; however, when it proceeds to parse its elements, none of them are included by default. To ensure that only properties matching the specified expressions are included in the json output, you must configure the includeProperties parameter in the json result.

For instance:

@Result(type="json", params = {"includeProperties", "msg,
  productsList\\[\\d+\\]\\.id,productsList\\[\\d+\\]\\.name,productsList\\[\\d+\\]\\.color"}) 

It's important to note that special characters need to be double escaped in this configuration.

Answer №2

To ensure only specific attributes of the Article model are accessible, they must be included in the whitelist of allowed properties.

For example, if the Article model has attributes such as id, name, and color, the configuration would appear as follows:

@Result(type = "json", params = { "includeProperties", 
                                  "msg, 
                                   productsList\\[\\d+\\]\\.id,
                                   productsList\\[\\d+\\]\\.name,
                                   productsList\\[\\d+\\]\\.color"})

In my opinion, utilizing a root object instead of includeProperties is preferable. However, in your scenario, consideration should be given to how to handle the inclusion of msg (which could potentially be dynamically generated client-side based on the List's outcome).

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 AngularJS to link ng-include in an ng-view HTML file

Currently, I am diving into AngularJs while also investigating the creation of a viral movie website for the new x-men film. The site in question is Trask Industries (http://www.trask-industries.com/#/innovation), where the navigation system seems to dynam ...

A JavaScript syntax problem arises when attempting to fetch data (an object) from a Laravel controller

Encountering a JavaScript syntax error in my .blade.php file when trying to access $data->modal This is my controller function: public function buku_all($page, $modal) {$data = (object) [ 'sidebar' => "pelayanan", ...

Managing JavaScript events in the console

Running a server for a video game in node.js where the console communicates with clients via websockets. I have a function to spawn enemies from a MySQL database, but I am encountering an error that seems to be related to a jQuery script... I want the scr ...

What is the function of the next and back buttons in AngularJS?

I need assistance with creating next and previous buttons in Angular. As I am new to programming, I have written a program that works when using a custom array $scope.data = []. However, it doesn't work when I use $http and I would appreciate any help ...

JavaScript lacks the power to persuade the mouse into altering its cursor

I am encountering an issue with my ASP.NET page that contains an Infragistics webgrid. I have implemented Javascript methods to handle the mouseover and mouseout events on the grid rows, changing the mouse cursor to a pointer and back to the default as use ...

Exploring ways to retrieve complete HTML content from a Single Page Application using AJAX?

Seeking assistance in obtaining the complete HTML generated by a Single Page Application built on AngularJS. $.get('http://localhost:3388/' + d.response.path, function (d) { $('#templateContainer').html(d); ...

Leveraging the power of ng-describe for comprehensive end-to-end testing using protractor

Recently, I stumbled upon a fantastic ng-describe package that simplifies the process of writing unit tests for AngularJS applications. It eliminates the need to remember and write all the boilerplate code required to load, inject, mock, or spy. Has anyon ...

Utilize NodeJS API to convert a base64 data string into a downloadable PDF file

My NodeJS API is set up to communicate with another API and fetch a data object in the form of a Base64 string. The client making the API call needs to be able to download a PDF file generated from this base64 data. What is the best way to return the dat ...

Numerous Voxels showcasing an array of unique textures. Optimal performance guaranteed

Is it possible to add multiple voxels (cubes with different textures) to the same scene in a more efficient manner? When I try to add more than 500 voxels, I encounter serious performance issues. Below is the code I am currently using: texture = createT ...

Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario: An API request from one service is creating multiple MongoDB documents in a single collection. For example: [ {_id: 1, test1: 2, test: 3}, {_id: 2, test1: 3, test: 4} ] Subsequently, a second service ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

Attempting to display an HTML image utilizing data storage

I'm currently working on building a database for animals at an animal shelter. I have created tables containing species information and when a user selects a specific species, all available animals are displayed. Now, I want users to be able to click ...

Nightwatch.js custom assertion for array comparison fails to function as expected

Utilizing the nightwatch-cucumber framework, which is built on top of Nightwatch.js, I am in the process of creating automated end-to-end tests. As a newcomer to 'JavaScript' and 'node.js', I encountered an error during the execution of ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

The LoopBack framework encountered an issue where it could not execute the 'post' method due to being undefined

As a newcomer to loopback and node.js, I have successfully created two models - Rating and RatingsAggregate. Utilizing the loopback explorer, querying and posting against the API has been smooth. In an attempt to establish basic business logic, I am curre ...

How can I implement automatic data loading in a drop-down list using Yii framework?

Currently, my focus is on studying the Yii book and encountering the following situation: My task is to create an article with various main categories and their corresponding sub-categories. For example: Technology (main) - Auto, - Mot ...

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Issue with AngularJS pagination: unable to detect the current page number

I am currently developing a compact application that showcases a JSON object of "users" in an HTML5 table. The application is built using Bootstrap 3 and AngularJS, and I have the intention to implement pagination for this table. Instead of having an arra ...

Accessing nodejs environment variables in a VueJS single page application

Creating a single page application with the use of Vue, running it with nodejs, and encapsulating it in a docker container poses an interesting challenge. In an attempt to adhere to the principles outlined in the 12 factor app methodology, one is advised t ...