Receive HTML Table in Controller (Springmvc)

Asked

Viewed 121 times

1

Good morning,

I have a page where the digital user 3 information.

<input type="text" id="info01">
<input type="text" id="info01">
<input type="text" id="info01">

When typing the 3, via javascript I perform a calculation and create a table below dynamically, with a structure similar to the one below.

<table>
   <thead>
      <tr>
         <td>Numero</td>
         <td>Valor</td>
         <td>Data</td>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>1</td>
         <td><input type="text" value="10.00"></td>
         <td><input type="text" value="09/07/2015"></td>
      </tr>
      <tr>
         <td>2</td>
         <td><input type="text" value="15.00"></td>
         <td><input type="text" value="12/07/2015"></td>
      </tr>
   </tbody>
</table>

As you can see, there are two table columns that are subject to change after generated.

My problem is, like, at the time of page Submit, receive and break this table inside the controller, to insert into the database.

Additional details: When entering the page, I send by the controller a "list" object, which is the list of an obj with the same structure that the table receives (Number, Value, Date)

Is there a way I can popular this session object, via javascript ? Or some way to receive the entire table in the Controller and loop it in the same ? I cannot simply generate the table, assign the same values to an array and send it to an Hidden, because if the user changes the values, they will be divergent.

  • That example shows a solution to your problem using the library JSoup. With this library, you can get the entire table in Java and iterate on its elements.

  • The only way you can send this data to the controller is by submitting a form? Could it be via Ajax? Via ajax I can present a solution to this. Here at the company I work with Springmvc also and I’ve been through something similar.

  • I think via ajax would also work onluiz, so I would send the data and return a java object via ajax and demonstrate the list from a loop in the object

1 answer

0

Hail!

If it is an option, I suggest you review its functionality so that instead of sending the table created dynamically whole via form, manipulate the DOM using a framework for templates.

You can use frameworks like Knockoutjs or Angularjs. They will abstract much of their work in manipulating elements of their HTML and interaction with the Controllers via Ajax.

This example using Knockoutjs is very close to what you’re asking for:

Table template

<h2>Your seat reservations (<span data-bind="text: seats().length"></span>)</h2>

<table>
    <thead><tr>
        <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
    </tr></thead>
    <tbody data-bind="foreach: seats">
        <tr>
            <td><input data-bind="value: name" /></td>
            <td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
            <td data-bind="text: formattedPrice"></td>
            <td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
         </tr>    
    </tbody>
</table>

<button data-bind="click: addSeat, enable: seats().length < 5">Reserve another seat</button>

<h3 data-bind="visible: totalSurcharge() > 0">
    Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>

Manipulation via Knockoutjs

// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);

    self.formattedPrice = ko.computed(function() {
        var price = self.meal().price;
        return price ? "$" + price.toFixed(2) : "None";        
    });    
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];    

    // Editable data
    self.seats = ko.observableArray([
        new SeatReservation("Steve", self.availableMeals[0]),
        new SeatReservation("Bert", self.availableMeals[0])
    ]);

    // Computed data
    self.totalSurcharge = ko.computed(function() {
       var total = 0;
       for (var i = 0; i < self.seats().length; i++)
           total += self.seats()[i].meal().price;
       return total;
    });    

    // Operations
    self.addSeat = function() {
        self.seats.push(new SeatReservation("", self.availableMeals[0]));
    }
    self.removeSeat = function(seat) { self.seats.remove(seat) }
}

ko.applyBindings(new ReservationsViewModel());

Server interaction can be done via Ajax using jQuery:

// (...) suprimi o restante e recuperei o código abaixo de outro exemplo. substitua o "tasks" por "reservations" da listagem acima.
self.save = function() {
        $.ajax("/tasks", {
            data: ko.toJSON({ tasks: self.tasks }),
            type: "post", contentType: "application/json",
            success: function(result) { alert(result) }
        });
    };

// Load initial state from server, convert it to Task instances, then populate self.tasks
$.getJSON("/tasks", function(allData) {
     var mappedTasks = $.map(allData, function(item) { return new Task(item) });
    self.tasks(mappedTasks);
});    

Your data will be sent to the server in a structured form and you can handle this data in the way that suits you.

This other article makes a good introduction to Knockoutjs. If you prefer also have a interactive demo (in which the above example was extracted).

PS: Sorry I don’t put more links to the cited frameworks, I don’t have enough reputation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.