简体   繁体   中英

How to retrieve “Grouped” items from HTML form using Servlet?

I am having an issue with retriving "grouped" data from HTML form to servlet. I will describve the scenario below.

In companies, they record the salary of the employees once a month.When they record it, they do not do it by visiting each an every employees personal "profile" (or whatever according to the system). Instead what they do is apply the salaries of all of them in one page.

To do the above thing they prefer excel like tabular sheets.

Now, I have a html form, where the form content is a table. One row is dedicated to a one employee.

Below is my form.

<%-- 
    Document   : index2
    Created on : Mar 5, 2015, 10:04:45 AM
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form method="post" action="EmployeeSampleServlet">
            <table border="1" style="width:100%">
                <thead>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Salary</th>
                </thead>
                <tbody name="tableBody" value="1">
                    <tr>
                        <td><input type="text" name="nameTxt" style="width:100%"/></td>
                        <td><input type="text" name="positionTxt" style="width:100%"/></td>
                        <td><input type="text" name="salaryTxt" style="width:100%"/></td>
                    </tr>
                </tbody>
                <tbody name="tableBody" value="2">
                    <tr>
                        <td><input type="text" name="nameTxt" style="width:100%"/></td>
                        <td><input type="text" name="positionTxt" style="width:100%"/></td>
                        <td><input type="text" name="salaryTxt" style="width:100%"/></td>
                    </tr>
                </tbody>
                <tbody name="tableBody" value="3">
                    <tr>
                        <td><input type="text" name="nameTxt" style="width:100%"/></td>
                        <td><input type="text" name="positionTxt" style="width:100%"/></td>
                        <td><input type="text" name="salaryTxt" style="width:100%"/></td>
                    </tr>
                </tbody>
                <tbody name="tableBody" value="4">
                    <tr>
                        <td><input type="text" name="nameTxt" style="width:100%"/></td>
                        <td><input type="text" name="positionTxt" style="width:100%"/></td>
                        <td><input type="text" name="salaryTxt" style="width:100%"/></td>
                    </tr>
                </tbody>
                <tbody name="tableBody" value="5">
                    <tr>
                        <td><input type="text" name="nameTxt" style="width:100%"/></td>
                        <td><input type="text" name="positionTxt" style="width:100%"/></td>
                        <td><input type="text" name="salaryTxt" style="width:100%"/></td>
                    </tr>
                </tbody>
            </table>
            <br/>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

As you can see, I have wrapped every row with a <tbody> . The value attribute of the <tbody> will contain the employee id.

Once the form is submitted, the below servlet will capture it.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EmployeeSampleServlet extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String[]empId = request.getParameterValues("tableBody");

        for(int i=0;i<empId.length;i++)
        {
            out.println(empId[i]);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

What I was trying is get the value attribute of <tbody> (so I can identify the id of the employee) and get the data inside that <tbody> . However this didn't work, because I ended up with NullpointerException because it failed to read the <tbody> value.

So, how can I pass the data from table to servlet where it can clearly understand that one row is representing data belong to a one employee? If this is not the way to do it, I am also open for other methods.

That is obviously not going to work as only the input field values are submitted to the server.

You will need to discriminate the names of each input field in some way as currently you cannot match these to individual employees:

I assume you generate the table from some kind of list of employees so you could do this something like below:

<tr>
     <td><input type="text" name="nameTxt_${employee.employeeId}" style="width:100%"/></td>
     <td><input type="text" name="positionTxt_${employee.employeeId}" style="width:100%"/></td>
     <td><input type="text" name="salaryTxt_${employee.employeeId}" style="width:100%"/></td>
</tr>

Now instead of receiving a bunch of random parameters 'nameTxt' etc., you reeive 'nameText_21', 'salaryText_21' etc. and have a means to identify the input with an employee. How you do this will depend on whether you have the list of Employees available in the Servlet on form submission.

eg

//employees = load the same list originally loaded for edit
for(Employee e : employees){
   e.setSalary(Double.parseDouble(request.getParameter("salaryTxt_" + e.getid())));
}

Otherwise you will need to iterate the parameters for some field and proceed that way.

for(String s: request.getParameterNames()){
  if(s.startsWith("nameTxt")){
     //extract suffix
     //load the employee with corresponding ID
     //get the other params with same id
  }
}

Look the below HTML, this will get all the table row-wise value and convert that as a json array. Now you can pass this array to servlet via ajax.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>

<table border="1"   id="mytable" border="1" >
            <thead>
                <th>Name</th>
                <th>Position</th>
                <th>Salary</th>
            </thead>
            <tbody>
                <tr>
                    <td><input type="text" name="nameTxt" value="12" /></td>
                    <td><input type="text" name="positionTxt" value="13" /></td>
                    <td><input type="text" name="salaryTxt" value="14" /></td>
                </tr>
                <tr>
                    <td><input type="text" name="nameTxt" value="21" /></td>
                    <td><input type="text" name="positionTxt" value="22" /></td>
                    <td><input type="text" name="salaryTxt" value="23" /></td>
                </tr>
                <tr>
                    <td><input type="text" name="nameTxt" value="31" /></td>
                    <td><input type="text" name="positionTxt" value="32" /></td>
                    <td><input type="text" name="salaryTxt" value="33" /></td>
                </tr>
                <tr>
                    <td><input type="text" name="nameTxt" value="41" /></td>
                    <td><input type="text" name="positionTxt" value="42" /></td>
                    <td><input type="text" name="salaryTxt" value="43" /></td>
                </tr>
                <tr>
                    <td><input type="text" name="nameTxt" value="51" /></td>
                    <td><input type="text" name="positionTxt" value="52" /></td>
                    <td><input type="text" name="salaryTxt" value="53" /></td>
                </tr>
            </tbody>
        </table>
        <br/>
        <input type="button" value="Submit" onclick="convertValuesToJson();">

</body>
</html>

And you script looks like,

<script>
    function convertValuesToJson(){

        var myStringArray = [];
        // Iterate each row
        $('#mytable tbody tr').each(function() {
            var myObject = new Object(); 
            myObject.name = $(this).find("input[name='nameTxt']").val();
            myObject.position = $(this).find("input[name='positionTxt']").val();
            myObject.salary = $(this).find("input[name='salaryTxt']").val();
            myStringArray.push(JSON.stringify(myObject));
        });

  // function for ajax goes here...
    jQuery.ajax({
      url: "ServletURL",
      type : 'POST',
      dataType: "json",
      data : {"myData" : myStringArray},
      error : function(jqXHR, textStatus, errorThrown) {
            alert("error occurred");
      }
   });
}
</script>

See my updated Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM