2

I have a table that dynamically generates values from my database. The list variable is an arrayList of some Object

 <table border="1">
                     <tr>
                        <th>Username</th>
                        <th>Full Name</th>
                        <th>Status</th>
                        <th>Action</th>
                     </tr>

                        <%for(int x = 0; x <list.size(); x++) {%>
                        <tr>
                        <td><% out.println(list.get(x).getUsername()); %></td>
                        <td><%out.println(list.get(x).getFirstname() + list.get(x).getMiddleinitial() + list.get(x).getLastname());%></td>
                         <td><% out.println(list.get(x).getStatus()); %></td>
                          <td> 
                              <form action="ViewManager" method="POST">
                                   <input id="button" type="submit" value="View" >
                              </form>
                              <form action="LockManager" method="POST">
                                   <input id="button" type="submit" value="Lock" >
                              </form>
                              <form action="DeleteManager" method="POST">
                                   <input id="button" type="submit" value="Delete" >
                              </form>

                          </td>
                        </tr>
                        <% }%>


                    </table>

What I want is to capture the username of the certain row in where I pressed the button and pass it to a servlet.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1

Just pass it as an additional request parameter with help of a hidden input element.

E.g.

<form action="ViewManager" method="POST">
    <input type="hidden" name="username" value="<%= list.get(x).getUsername() %>" />
    <input id="button" type="submit" value="View" >
</form>

It's available as

String username = request.getParameter("username");

Unrelated to the concrete problem, this is an oldschool way of writing JSPs. The above approach is also sensitive to XSS attacks. Java/JSP scriptlet doesn't have builtin facilities to prevent that. Consider using JSTL <c:forEach> to iterate over the list and fn:escapeXml() to escape user-controlled data to prevent XSS attack holes.

<c:forEach items="${users}" var="user">
    ...
    <input type="hidden" name="username" value="${fn:escapeXml(user.username)}" />
    ...
</c:forEach>

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555