【问题标题】:Pass the details of Multiple rows from JSP to Servlet将多行的详细信息从 JSP 传递给 Servlet
【发布时间】:2012-04-16 15:38:56
【问题描述】:

我的 JSP 文件中有一个员工列表,我为每个员工提供了一个更新位置的选项(下拉菜单)。结果被传递给“SaveTubeDetails”servlet,它负责保存数据。

这是我目前使用的代码:

<form action="SaveTubeDetails" method="POST">
 <table>
 <% 
   for(Iterator<Employee> itr = employeeArr.iterator(); itr.hasNext();){ 
   Employee emp= itr.next();
 %> 

<tr> 
  <td>
  <select name="location">
  <% for(int count=0; count<locArr.size(); count++){ %>     
  <option value="<%= locArr.get(count) %>" ><%= locArr.get(count) %></option>   
  <%} %>
  </select>
  </td> 
</tr>
</table>
</form>

我的问题是,如何将其保存为可以传递给 Servlet 的员工列表?

注意:我没有使用 Spring 和 Hibernate。而且我知道不应该使用 scriptlet,但我别无选择,因为我正在更新现有代码。虽然这里只显示了 Employee 的 Location 详细信息,但实际上还有更多的列,例如 Age、DOB 等。

【问题讨论】:

    标签: java jsp jakarta-ee servlets


    【解决方案1】:

    在您的特定示例中,所有提交的值都是 HttpServletRequest#getParameterValues() 可用的字符串数组,其顺序与输入在 HTML 标记中出现的顺序完全相同。

    String[] location = request.getParameterValues("location");
    // ...
    

    作为替代方案,您可能需要考虑在输入名称中包含员工 ID,以避免任何潜在的竞争条件(例如,在显示表单和显示表单之间的不同最终用户从数据库中删除员工时)处理表单提交):

    <select name="location_<%=emp.getId()%>">
    

    然后可以根据现有员工列表在 servlet 中收集,如下所示:

    List<Employee> employees = employeeService.list();
    
    for (Employee employee : employees) {
        String location = request.getParameter("location_" + employee.getId());
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-16
      • 2015-01-18
      • 2016-08-08
      • 1970-01-01
      • 2011-01-16
      • 2016-11-24
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      相关资源
      最近更新 更多