简体   繁体   English

如何使用Servlet从HTML表单中检索“分组”项目?

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

I am having an issue with retriving "grouped" data from HTML form to servlet. 我在将“分组的”数据从HTML表单检索到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. 现在,我有一个html表单,其中表单内容是一个表。 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> . 如您所见,我用<tbody>包裹了每一行。 The value attribute of the <tbody> will contain the employee id. <tbody>value属性将包含员工ID。

Once the form is submitted, the below servlet will capture it. 提交表单后,下面的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>

}

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> . 我正在尝试获取<tbody>value属性(以便我可以识别员工的ID)并获取该<tbody>内部的数据。 However this didn't work, because I ended up with NullpointerException because it failed to read the <tbody> value. 但是,这没有用,因为我最后NullpointerExceptionNullpointerException因为它无法读取<tbody>值。

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? 因此,如何将数据从表传递到servlet,以便它可以清楚地理解代表数据的一行属于一个雇员? 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. 现在,您不再需要接收一堆随机参数“ nameTxt”等,而可以重新获取“ nameText_21”,“ salaryText_21”等,并且可以通过员工识别输入。 How you do this will depend on whether you have the list of Employees available in the Servlet on form submission. 如何执行将取决于表单提交时Servlet中是否有可用的Employees列表。

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. 看下面的HTML,它将获取所有表的行值并将其转换为json数组。 Now you can pass this array to servlet via ajax. 现在,您可以通过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>

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 查看我更新的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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