【问题标题】:How to retrieve "Grouped" items from HTML form using Servlet?如何使用 Servlet 从 HTML 表单中检索“分组”项目?
【发布时间】:2015-05-06 09:58:44
【问题描述】:

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

在公司中,他们每月记录一次员工的工资。记录时,他们不会通过访问每个员工的个人“资料”(或根据系统的任何内容)来记录。相反,他们所做的是将所有人的薪水应用到一个页面中。

为了做上述事情,他们更喜欢 Excel 之类的表格。

现在,我有一个 html 表单,表单内容是一个表格。一排专用于一名员工。

下面是我的表格。

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

如您所见,我用&lt;tbody&gt; 包裹了每一行。 &lt;tbody&gt;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>

}

我正在尝试获取&lt;tbody&gt;value 属性(这样我就可以识别员工的ID)并获取&lt;tbody&gt; 中的数据。但是这不起作用,因为我最终得到了NullpointerException,因为它未能读取&lt;tbody&gt; 值。

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

【问题讨论】:

  • 您可以在输入隐藏元素中写入员工 id .. 在提交表单时可以自动将其传递给 servlet。 标签没有属性名称和值。
  • @BrijeshBhatt:我认为你没有明白我的意思。即使我这样做了,我怎样才能找到该行中的其余列是否属于同一个id?
  • 我认为您需要员工 id 作为我在上面编写的 servlet 中的参数。但是您要说的是,为此,您必须使用 javascript 或 jquery 准备一个查询字符串,然后将其发布到 servlet。这将解决您的问题。
  • 你错了。 tbody 不是文本框或复选框之类的元素,您无法从表单中获取值。你只需要身份证?因此您可以将其用于业务逻辑。否则你需要整行?
  • @VinothKrishnan:整行,可以识别该行属于哪个员工。

标签: java html jsp servlets web-applications


【解决方案1】:

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

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

我假设您从某种员工列表中生成表格,因此您可以执行以下操作:

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

【讨论】:

  • 这看起来很有希望,我会检查一下。
【解决方案2】:

查看下面的 HTML,这将获取所有表格的行值并将其转换为 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

【讨论】:

  • 我可能遗漏了一些东西,但是提交的值如何与特定员工相关联?
  • 您可以在隐藏文本框中为每一行设置员工 ID,并将这些 ID 添加到 json 数组中。安静简单..看到Demo住在这里..
  • 谢谢。会检查的。
  • @AlanHay SO中已经发布了n个答案来处理java中的json数组。请参阅link1link2link3。希望这会有所帮助。
猜你喜欢
相关资源
最近更新 更多
热门标签