Sending a collection of nested arrays to an MVC controller

Currently, I am utilizing spring MVC and have the requirement to transmit data to my controller on the backend server.

@RequestMapping(value="/project/update")
public @ResponseBody projectWebForm update(HttpServletRequest request,
        HttpServletResponse response,
        @RequestBody projectWebForm input){

        ..............

        }

To accomplish this task, I am making use of the @RequestBody annotation to bind my fields to a class named projectWebForm

Inside the projectWebForm class, there are 3 fields

private String name;
private String age;
private List<List<Data>> list;

In addition, I have defined a Data class as follows

 public class Data{
  private String data1;
  private String data2;

getters setters..... 
}

Now, in a jsp file, I am implementing ajax functionality to send data to the controller

function update(name,age){
var option={
    headers:{'Content-type':'application/json;charset=utf-8'},
    contentType:'application/json;charset=utf-8',
    dataType:'json',
    async:true,
    type:'post',
    data:JSON.stringify({
        name:name,
        age:age,
        list:____________ <---- ????????
    }),
    url:'<%=request.getContextPath()%>/project/update.do',
    success:function(response){
        ......
        }
    },
};
$.ajax(option);
};

I have successfully passed the name and age to the controller since they are both Strings. However, now comes the challenge of transmitting a list of lists. How can I structure my list so that it can be mapped correctly to the RequestBody? What should the JSON format be for sending this information to the RequestBody? Can you provide an example?

Answer №1

JavaScript

var itemList = new Array();

var itemData = {
    data1 : fetchData1,
    data2 : fetchData2
};

itemList.push(itemData);

data: JSON.stringify({
        name: itemName,
        age: itemAge,
        list: itemList
    }),

class

public class Example {

   private String itemName;
   private String itemAge;
   private List<dataItem> itemList;

    ... s,g

}

controller

@RequestMapping(value="/project/update", method = RequestMethod.POST)
public @ResponseBody String update(HttpServletRequest request, @RequestBody Example example){

      .............. // break point
      return "";

}

Please verify the model(Example).

Answer №2

function HandleFormData( form ){
var formData = $(form).serialize();
att=$(form).attr("action") ;
$.post(att, formData).done(function(response){

     var errorInfo="";

      if(response.status == "SUCCESS"){
          window.location.href="/";
      }
});
return true;}

Manage form data serialization and transmission to the server in Spring MVC

    <form name="myForm" th:object="${demo}" th:action="@{/demo}"  method="post"
    class="stdform" id="triggerform">

            <div class="form-group">
         <label for="usr">Name:</label>
     <input type="text" th:field="*{name}" class="form-control" />
     </div>
    <div class="form-group">
         <label for="usr">hobbies:</label>
            <input  th:field="*{hobbies[0].hobbiename}" type="text" class="form-control"   />
             <input th:field="*{hobbies[1].hobbiename}" type="text" class="form-control"   />
             <input th:field="*{hobbies[2].hobbiename}" type="text" class="form-control"  />
             <input th:field="*{hobbies[3].hobbiename}" type="text" class="form-control"  />
             <input th:field="*{hobbies[4].hobbiename}" type="text" class="form-control"   />
             <input th:field="*{hobbies[5].hobbiename}" type="text" class="form-control"   />


     </div>



            <button type="button"  onclick="return HandleFormData(this.form)" class="btn btn-primary">Get Started</button>

</form>

The controller section

    @RequestMapping(value = "/demo", method = RequestMethod.GET)
public ModelAndView demo(HttpServletRequest request) {
        logger.info("Welcome to getInboxMessage Method inside the MessageController ");
        Profile profile=(Profile)request.getSession().getAttribute("profile");
        ModelAndView model=new ModelAndView("test");
        model.addObject("demo", new Demo());
        return model;

    }

@RequestMapping(value = "/demo", method = RequestMethod.POST)
public ModelAndView demopostdata(@ModelAttribute Demo demo,HttpServletRequest request) {
        logger.info("Welcome to getInboxMessage Method inside the MessageController ");
        Profile profile=(Profile)request.getSession().getAttribute("profile");
        ModelAndView model=new ModelAndView("test");
        model.addObject("demo", new Demo());
        return model;

    }

This is a simple approach to reduce the amount of jQuery coding needed

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

Updating part of a page while also changing the navigation

Apologies in advance, as this is my first attempt at coding a website. I have a specific need where I want to update only one div on my web page when a link in the navigation bar is clicked. <body> <div id="wrapper"> <header id= ...

Using AJAX in TYPO3's TCA forms to create dynamic dropdown menus

I have created two drop down lists in my TCA forms. The first one is called Campus and the second one is called Department. I want the options in the Department list to change based on the selection made in the Campus list. Essentially, the items in the De ...

Exploring the concept of Model Binding in WebAPI through JSON Data

Currently, I am in the process of developing an application using Durandal along with WebAPI as the server. Everything seems to be running smoothly until the POST or PUT methods are invoked while working with a KendoUI grid. The data from the server displa ...

JavaScript API for Outlook appointment object

Is there a way to change the appointment busy status "show as" to out of office using JavaScript in an Outlook web add-in? Also, how can I alter the value of all day event to true (tick it) using JavaScript in an Outlook web add-in? Any insights would be ...

A guide on incorporating oAuth 2.0 into Tizen

Currently, I am in the process of incorporating Google authentication using oAuth 2.0 in Tizen. I am following the guidelines provided here. Despite successfully obtaining the user code as instructed in the link, I keep receiving an invalid request error w ...

What is the method for retrieving a value using the Angular forEach function?

I'm encountering an issue with retrieving values from an angular forEach loop. Below is the data I am working with: vm.memberDetails={ "member": [ { "firstName": "HARRY UTTWO", "lastName": "POTTER", } ...

JavaScript Popup Box Failing to Trigger

Snippet of Code: <form method="post" id="cp_ind_form"> // several input fields here... <input type="submit" name="update_submit" value="Update" /> <input type="submit" name="delete_submit" value="Delete" onclick="deleteConfi ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

Tips on accessing files saved in a one-to-many connection using Mongoose

I have multiple Schemas set up for Shops and Products. Each shop can have a variety of products, and I currently have 5 different shops with their own unique product listings. While I am able to save the products and find their corresponding IDs within eac ...

Function generator within a component

I have a class-based component and I need to declare a generator function for an API call inside it without using fetch.then. Below is the code snippet: class SearchField extends React.Component { componentWillUnmount() { this.props.clearSearchStat ...

Tips for resolving the problem of Google Maps repeatedly appearing when utilizing the Auto-Loading feature

I need help understanding the issue that arose when loading the Google Maps API. "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." This error occurred while attempting to automatically load the API. B ...

What is the best way to display the L.featureGroup using an array of coordinates?

Is there a way to render the L.featureGroup using an array of coordinateRoute from the data.json file, and then trigger it with a button labeled "Snake it!"? Essentially, I want to be able to click on "snake it!" which will have its own unique id, causing ...

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

Utilizing Firebase push notifications with multiple google-service.json files within a single Android Studio project

In a scenario where we have a single project but require multiple Firebase push notification and google-server.json files, how can we effectively manage these multiple files within Android Studio? ...

Exploring the possibilities of combining DOM and Express in web development

app.post('/result.html',function(req,res){ var num1 = req.body.Num1 ; var num2 = req.body.Num2 ; var operator = req.body.Operator ; var result =0 ; switch (operator) { case '+': result = Number(num1)+Number(num2) ; ...

Swapping items within Angular's forEach()

I am working with an array of objects and using a forEach() function in my code. Here is the structure: $scope.things = [ {x: 2}, {x: 4}, {x: 5} ]; angular.forEach($scope.things, function(thing) { //You can uncomment one line at a time ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Trouble with VueJS refresh functionality

I am facing an issue with a method that needs to run on route load. Despite attempting to call it from the updated hook, it is not functioning as expected. Additionally, I have encountered an ESLint error. methods: { getDeals (key, cb) { this.dealsR ...