0

I have html table in jsp page the loads data from database dynamically then I wan to save all data in the table into database through servlet. now my problem is i am having a jsp page which display a table of data from a servlet with checkbox in it, i have to send that checked contents to the servlet for updating to the database, how to do that.

thanks in advance and this is my table

<form action="showKwh" method="POST">

    <input type="submit" value="show"/>

    <table id="adminTable" class="detailsTable">

        <tr class="header">
            <th colspan="4">Kilowat Entry</th>
        </tr>

        <tr class="tableHeading">
            <td></td>
            <td>customer id</td>
            <td>name</td>

            <td>group</td>
            <td>kwh</td>



            <td>kwd</td>

        </tr>

        <c:forEach  var="cust" items="${customerKwh}" varStatus="iter">
            <tr id="${cust.id}" class="${((iter.index % 2) == 1) ? 'lightBlue' : 'white'} tableRow">
                <td><input type="checkbox" name="check1" class="checker" value="ON" /></td>
                <td id="id?${customer.id}">${cust.id}</td>
                <td >${cust.name}</td>
                <td >${cust.type}</td>

                <td >${cust.kwh}</td>



                <td><input type="text" name="txt" size="8" id="kwd${cust.id}" value="${param.value}" class="name1"  /></td>

            </tr>
        </c:forEach>
    </table>
</form>
Abdirazack
  • 43
  • 1
  • 2
  • 11
  • what is action="showKwh" i presume its mapping to a servlet. so you will need to create a separate servlet class and use jdbc code there to persit the data in db. you can set the table attribute in your jsp and fetch inside servlet. also you need to provide a mapping for "/showKwh" in your web.xml. checkout the code in this link http://www.tutorialspoint.com/servlets/servlets-database-access.htm – vikeng21 Dec 01 '14 at 05:06
  • thanks for your answer but I have no doubt how to use servlet and my URl "showKwh" is working but I need a way that read or send whole data of html table into servlet – Abdirazack Dec 01 '14 at 05:10

2 Answers2

1

Either you put all data that you need to post back upon submit into form fields and browser sends it, or you use some javascript like jQuery to manipulate your html table's DOM, extract data on the clientside and send it via ajax request in form of JSON or XML to be parsed serverside.

It's quite strange requirements, though. Since data in the table originates from the same server that processes response, it would be sufficient to respond with a set of row identifiers, by which the server would recognize full row data.

You could pass these identifiers with checkboxes' values: <input type="checkbox" name="check1" class="checker" value="${cust.id}" />. Then, following HTML standard, only checkboxes having checked or checked="checked" attribute would be included in response. Then your servlet can process all checked checkboxes and get all needed identifiers.

Extracting form data with jQuery. First, add to your <td>'s with data classes that would mark contained data, so we can select it with jQuery:

<td class="customerName">${cust.name}</td>
<td class="customerType">${cust.type}</td>
...and so on.

Include jQuery into JSP with element <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> added before closing tag. Then add another script element on the page containing our script. Here is an example:

<html>
<head>

</head>
<body>

<form action="showKwh" method="POST">

    <input type="submit" value="show"/>

    <table id="adminTable" class="detailsTable">

        <tr class="header">
            <th colspan="4">Kilowat Entry</th>
        </tr>

        <tr class="tableHeading">
            <td></td>
            <td>customer id</td>
            <td>name</td>

            <td>group</td>
            <td>kwh</td>


            <td>kwd</td>

        </tr>

        <tr id="123" class="lightBlue tableRow">
            <td><input type="checkbox" name="check1" class="checker" value="123"/></td>
            <td id="id?123" class="customerId">123</td>
            <td class="customerName">Ivan</td>
            <td class="customerType">Person</td>

            <td class="customerKWH">54321</td>


            <td><input type="text" name="txt" size="8" id="kwd123" value="98765" class="name1"/></td>

        </tr>
    </table>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () { //launch this code after the whole DOM is loaded
        $("form").submit(function (event) { // function to process submitted table
                    var tableData = []; // we will store rows' data into this array
                    $("#adminTable") // select table by id
                            .find(".tableRow") // select rows by class
                            .has(":checked") // select only rows with checked checkboxes
                            .each(function () { // for each selected row extract data               
                                var tableRow = {};
                                var jRow = $(this);
                                tableRow.customerId = jRow.find('td.customerId').text();
                                tableRow.customerType = jRow.find('td.customerType').text();
                                tableRow.customerKWH = jRow.find('td.customerKWH').text();
                                tableRow.costomerKWD = jRow.find('input.name1').val();
                                tableData.push(tableRow);
                            });

                    $.post(
                            "http://google.com", /*url of consuming servlet*/
                            {tableData: tableData}, /*data*/
                            function () {
                                alert("Success!");
                            }, /*function to execute in case of success*/
                            "json" /* data type */
                    );
                    event.preventDefault(); //Prevent sending form by browser
                }
        );


    });
</script>
</body>
</html>

To process table values submitted by form in browser, you can consider the following approach.

HttpServletRequest inherits from ServletRequest method getParameterMap() which returns Map. ( http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameterMap() ). You could parse it using some parameter names convention. For example:

Map<String, String[]> tableData = getParameterMap();
String[] idsToUpdate = tableData.get("selectedIds");
for (String id : idsToUpdate){
    String kwdParamName = "kwd"+id;
    String kwd = tableData.get(kwdParamName)[0];
}

One way or the other, you should parse request data somehow. Both (JSON-based and form-based) have their pro et contra. You should chose which one produces more clean and robust solution. Maybe, more pleases you aesthetically. And last, but not least, what is your client context: doest it have javascript enabled, is it single-page application or round-trip. In single-page it is more usual way to pass data back and forth via JSON. In round-trip - maybe form-based would be more practical.

iTollu
  • 999
  • 13
  • 20
  • thanks brother, could you please show me in clearer way please thought I am beginner – Abdirazack Dec 01 '14 at 05:53
  • What particular details do you need? – iTollu Dec 01 '14 at 05:58
  • how to extract data of the whole table on the client side and send it via ajax request in form of JSON to be parsed serverside. thanks your reply – Abdirazack Dec 01 '14 at 06:03
  • A'll update my answer with code, because I can't format it within comments. – iTollu Dec 01 '14 at 06:08
  • I've updated answer. You can see data that is sent along with ajax request using browser's developer tools, namely "Network" tab in Chrome or Firefox dev tools. – iTollu Dec 01 '14 at 07:11
  • Thank you very much iTollu, this is impressive but after sending table data into servlet, how to can I deal with it, please show some code in servlet. – Abdirazack Dec 01 '14 at 07:59
  • thanks, you really helped me about client side solution and I will try to do rest. thanks any way – Abdirazack Dec 01 '14 at 08:30
  • If you choose to send JSON data, then your servlet (HttpServlet) will override doPost method. There you get post request content and you have to process it somehow. Look towards Jackson processor (http://wiki.fasterxml.com/JacksonHome ). There are good turorials there. You can parse JSON data to get java objects and work with them. – iTollu Dec 01 '14 at 08:43
  • But I still recommend to send only id's of selected rows (via checkboxes' values) and input data (i.e. form data), while data, that is not supposed to be changed by client, should be taken by id on the server-side. If you send only form data in request, then standard methods from servlet api apply here without the need to parse JSON. See another two answers for examples. Servlet 3.0 spec can be found here: http://download.oracle.com/otndocs/jcp/servlet-3.0-mrel-eval-oth-JSpec/ – iTollu Dec 01 '14 at 08:46
  • thanks once again, I know get parameter in servlet like this, ex String name=request.getParameter("name");, but in this case of dealing with whole tabledata should I use like this, String tableDate=request.getParameterValues("tableDate");, any idea about than, please – Abdirazack Dec 01 '14 at 08:48
  • what I need in the servlet is to get table'data and then pass them into another java method to save them into mysql database – Abdirazack Dec 01 '14 at 08:58
  • Please try to do this, I need it very much, what i need from you is to get parameters sent from ajax in servlet and pass these parameters into another java class method, the rest I will do it thanks once more, I wait you. – Abdirazack Dec 01 '14 at 09:04
  • Look at Jackson data binding and tree model, please: https://github.com/FasterXML/jackson-databind/ . Their examples are quite good. I just didn't have practice with Jackson, so these tutorial will explain and demonstrate the subject better. The steps would be: override HttpServlet's `doPost()`, get reader with `HttpServletRequest.getReader()`, create Jackson's ObjectMapper for this reader, either map it to array of objects, representing table rows, or iterate througt it, instantiating these objects on each iteration and performing needed actions. After completing respond with some 'Ok' data. – iTollu Dec 01 '14 at 09:49
  • Thanks Mr Itollu for your help – Abdirazack Dec 01 '14 at 12:38
  • thanks Mr Itollu, your help did a great job for me, thanks – Abdirazack Dec 17 '14 at 05:21
  • You are welcome! Nice to know that it was helpful. – iTollu Dec 17 '14 at 05:31
0

As your input field (checkbox) is in for loop so all checkboxes will have the same name attribute. So you can get values for input fields having same name using following method available in HttpServletRequest.

String[] getParameterValues(String name)

In your case you can fetch all values using following statement-

request.getParameterValues("check1");
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
Sudhir Dhumal
  • 902
  • 11
  • 22
  • thanks Sudhir Dhumal, is there a way that I can read all data of html table in servlet or a way that I can get whole data of html data and then send them to servlet – Abdirazack Dec 01 '14 at 05:14