如何使用 Servlet 从 HTML 表单中检索 "Grouped" 项?

How to retrieve "Grouped" items from HTML form using Servlet?

我在将 "grouped" 数据从 HTML 表单检索到 servlet 时遇到问题。我将描述下面的场景。

在公司中,他们会记录一次员工的工资 month.When 他们记录下来,他们不会通过访问每个员工个人 "profile"(或根据系统进行的任何操作) ).相反,他们所做的是在一页中应用所有人的薪水。

要完成上述操作,他们更喜欢 excel 表格表格。

现在,我有一个 html 表单,其中表单内容是 table。一排专供一名员工使用。

下面是我的表格。

<%-- 
    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>

如您所见,我用 <tbody> 包裹了每一行。 <tbody>value 属性将包含员工 ID。

提交表单后,下面的 servlet 将捕获它。

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>

}

我尝试的是获取 <tbody>value 属性(这样我就可以识别员工的 ID)并获取 <tbody> 中的数据。但是这没有用,因为我最终得到了 NullpointerException 因为它无法读取 <tbody> 值。

那么,我怎样才能将数据从 table 传递到 servlet,它可以清楚地理解一行代表数据属于一名员工?如果这不是办法,我也愿意接受其他方法。

这显然行不通,因为只有输入字段值被提交到服务器。

您需要以某种方式区分每个输入字段的名称,因为目前您无法将这些名称与个别员工相匹配:

我假设您从某种员工列表中生成 table,这样您就可以执行如下操作:

<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>

现在,您接收的不是一堆随机参数 'nameTxt' 等,而是 'nameText_21'、'salaryText_21' 等,并且有办法识别员工的输入。如何执行此操作将取决于您在提交表单时是否在 Servlet 中有可用的员工列表。

例如

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

否则,您将需要迭代某些字段的参数并继续执行此操作。

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

查看下面的 HTML,这将获取所有 table 行值并将其转换为 json 数组。现在您可以通过 ajax.

将此数组传递给 servlet
<!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>

你的脚本看起来像,

<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>

查看我的更新Demo