Skip to content Skip to sidebar Skip to footer

The Way To Get A Value From A Hidden Type Correctly

in a html table i construct in each row an edit button like the following: retour.append('

Solution 1:

You can send the id parameter with the GET HTTP method in each row:

<a href="[URL]?id=[id]"><img src="edit.gif"/></a>

where:

  • URL is the URL to which you submit this form to and
  • id is what you build with "id_" + nomTab + "_" + compteur

Solution 2:

You can get the id from the HttpServletRequest request variable in doGet()/doPost() methods using the getParameter() method. Example: request.getParameter("edit"). "edit" is the name of the input field.

Your html code is not valid. You should quote your attributes. Also you might consider doing the html output in JSP instead of appending strings in a servlet.

Like Bruno said. It might be easyer to create href links width an id request parameter instead of forms with hidden input fields.


Solution 3:

You're unnecessarily overcomplicating things. First, HTML should not be emitted by a Servlet, but should be embedded as template in a JSP. Second, to achieve what you want, each button must sit in its own <form> element. Here's a kickoff example:

Servlet which loads the table data:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException) {
    List<Item> items = itemDAO.list();
    request.setAttribute("items", items);
    request.getRequestDispatcher("list.jsp").forward(request, response);
}

list.jsp which displays the table data:

<table>
    <c:forEach items="${items}" var="item">
        <tr>
            <td>${item.someProperty}</td>
            <td>
                <form action="servletUrl" method="post">
                    <input type="hidden" name="id" value="${item.id}">
                    <input type="submit" name="edit" value="edit">
                </form>
            </td>
        </tr>
    </c:forEach>
</table>

Servlet which processes the edit:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException) {
    Long id = Long.valueOf(request.getParameter("id"));
    Item item = itemDAO.find(id);
    request.setAttribute("item", item);
    request.getRequestDispatcher("edit.jsp").forward(request, response);
}

No need for Javascript hacks to pass the row ID.


Post a Comment for "The Way To Get A Value From A Hidden Type Correctly"