hazi
hazi

Reputation: 53

Sending selected object from JSP to Servlet

I am a beginner to Java EE and I have started to implement a small online book Store shopping cart example to learn and apply basic concepts. When user search for a book, it gives a list of suggested books then user starts to add to cart those by clicking the Add To Cart Button.

I have used hidden input type to send it.

Below is my JSP code.

  <% 
    List<BookDetails> newlist = new ArrayList<BookDetails>();    
    newlist = (List)session.getAttribute("currentSession");
  %>
    <table>
       <form name="DisplayResult" action="addToCartServlet">
    <tr>
       <td><b>Book</b></td><td><b>Price</b></td>
    </tr>

  <%
    for (int i = 0; i < newlist.size(); i++) 
    {
       BookDetails book1 =newlist.get(i);
  %>
  <tr>
   <td><%=book1.getBookName()%></td>
   <td><%=book1.getPrice()%></td>
   <td>
       <input type="hidden" name="ISBN" value="<%=newlist.get(i).getISBN()%>">
       <input type="submit" name="action" value="Add to Cart">
  </td>
  </tr>
  <% }%>
  </form>
  </table>  

I'm accessing it through servlet as below. String isbn= request.getParameter("ISBN") ;

But it every times takes only the first search result value for any button click. How can I get each unique ISBN for each book?

Upvotes: 0

Views: 729

Answers (2)

jmail
jmail

Reputation: 6134

he @Jigar Joshi telling right, at same method look like.

the text box as follows:

<form:input path="contacts[${status.index}].book" /> 

    <tr>
      <td align="center">${status.count}</td>
      <td><input name="contacts[${status.index}].book" value="${contact.book}"/></td>
      <td><input name="contacts[${status.index}].price" value="${contact.price}"/></td>
   </tr>

explanation of line is:

contacts[${status.index}].book 

Its will generate each rows as follows:

contacts[0].book // mapped to first item in contacts list
contacts[1].book// mapped to second item in contacts list
contacts[2].book// mapped to third item in contacts list

explanation of line is coding format:

<form:input path="contacts[${status.index}].book" />

Then instead of converting it to following HTML code:

<input name="contacts[0].book" />
<input name="contacts[1].book" />
<input name="contacts[2].book" />

It converts it into following:

<input name="contacts0.book" />
<input name="contacts1.book" />
<input name="contacts2.book" />

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240870

You need form per row to pass different data for each row


See

Upvotes: 1

Related Questions