Sending selected object from JSP to Servlet - java

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?

You need form per row to pass different data for each row
See
why business logic should be moved out of JSP?

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" />

Related

JSTL: Setting different values to a hidden attribute in a form inside a foreach on every iteration

I am iterating through a list on my JSP page using foreach. Based on this iteration, I set different values to table rows. In one column, there is a hyperlink which holds reference to a form so that onclick of this hyperlink, the form gets submitted. This form has a hidden attribute which should hold the value of a item in the list in the current iteration. Onclick, the form with this value of the list item in the hidden attribute gets submitted.
The problem is this that only the first item in the list is getting set to this hidden attribute in every iteration. The next value never gets assigned.
However, this is not the case for the other columns in the table. They have fresh values in each row/tuple.
<c:forEach items="${myList}" var="item">
<!--iterating through this list. Some code here-->
<form action="callthis.jsp" id="request_form" method="post" target="_blank">
<input type="hidden" id="requestxml" name="requestxml" value="${item.requestxml}" /></form>
<td>
<a href="javascript:document.getElementById('request_form').submit();"id="request">
requestXML </a>
</td>
<!--some code here-->
You have 2 options:
//1- Only one form
<form action="callthis.jsp" id="request_form" method="post" target="_blank">
<c:forEach items="${myList}" var="item">
<!--iterating through this list. Some code here-->
<input type="hidden" id="requestxml" name="requestxml" value="${item.requestxml}" />
<td>
requestXML
</td>
</c:forEach>
</form>
//2- render multiple forms with different ID using varStatus
<c:forEach items="${myList}" var="item" varStatus="status">
<!--iterating through this list. Some code here-->
<form action="callthis.jsp" id="form_${status.index}" method="post" target="_blank">
<input type="hidden" id="requestxml" name="requestxml" value="${item.requestxml}" /></form>
<td>
requestXML
</td>
</form>
</c:forEach>
You have to assign unique id to each form because there are multiple form with same id so it takes first one. Refer this code .This is just for example.
<c:forEach begin="1" end="5" var="item" varStatus="status">
<form action="callthis.jsp" id="request_form${status.index}" method="post"
target="_blank">
<input type="hidden" id="requestxml" name="requestxml" value="${item}" />
</form>
<td><a
href="javascript:document.getElementById('request_form${it‌​em}').submit();"
id="request"> requestXML </a></td>
</c:forEach>

Retrieve an array of parameters from a servlet [duplicate]

I am able to display an ArrayList of beans in a JSP form using JSTL by looping through the list and outputting the bean properties in a HTML input tag.
<c:forEach items="${listOfBeans}" var="bean">
<tr>
<td><input type="text" id="foo" value="${bean.foo}"/></td>
<td><input type="text" id="bar" value="${bean.bar}"/></td>
</tr>
</c:forEach>
How do I code the JSP so that when the page submits then the updated values are in the appropriate item of the the ArrayList?
Given this simplified model:
public class Item {
private Long id;
private String foo;
private String bar;
// ...
}
Here's how you can do it provided ${items} is List<Item>:
<c:forEach items="${items}" var="item">
<tr>
<td>
<input type="hidden" name="id" value="${item.id}" />
<input name="foo_${item.id}" value="${fn:escapeXml(item.foo)}" />
</td>
<td>
<input name="bar_${item.id}" value="${fn:escapeXml(item.bar)}" />
</td>
</tr>
</c:forEach>
(note the importance of fn:escapeXml() as XSS attack prevention)
So, basically, you need to set the item's unique identifier as a hidden input field in each row as shown in above snippet:
<input type="hidden" name="id" value="${item.id}" />
And you should in turn use this id as suffix of name of all input fields in the same row such as:
<input name="foo_${item.id}" ... />
In the servlet, you can collect all values of <input type="hidden" name="id" ...> from all rows by request.getParameterValues(). Just loop over it and then grab the individual inputs by id.
for (String id : request.getParameterValues("id")) {
String foo = request.getParameter("foo_" + id);
String bar = request.getParameter("bar_" + id);
// ...
}
You can also do this all without that id and grab all inputs by name as an array like so name="foo" and request.getParameterValues("foo"), but the ordering of request parameters is not under your control. HTML forms will send it in order, but the enduser can easily manipulate the order.
No need for JavaScript mess here.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
ServletRequest.getParameterMap() returns Map<String, String[]> and ServletRequest.getParameter() returns String?
Send an Array with an HTTP Get

Adding button and textbox dynamically in jsp page

<form:form action="approveAccount.html" method="GET">
<input type="submit" value="approvAll"/>
<p>Following Accounts are Pending to approve</p>
<c:forEach items="${accountIdList}" var="val">
<li>${val}</li>
</c:forEach>
</form:form>
val is the value that is fetched from database, I want to add a submit button and want to use this fetched value to do some stuffs, how many value get fetched is dynamically decided, how todo that.. here in this scenario, I am getting account id which admin needs to approv, so by adding textbox, admin can assign the role to the this account and then submit the to the database and this all happen with that clk of button
Suppose, in your service class, you have list of accountIds like this
ArrayList<Integer> accountIdList = new ArrayList<>();
accountIdList.add(1);
accountIdList.add(2);
accountIdList.add(3);
& you have added this list into HTTP Session object for further use like
session.setAttribute("accountIds",accountIdList);
In your JSP, you can then use JSTL for-each loop to create dynamic buttons & textboxes as below
<c:forEach var="ids" items="${session.accountIds}" varStatus="loop">
<input type="text" name="role${loop.index}" />
<input type="submit" value="<c:out value=${ids} />" />
</c:forEach>
I hope this helps.
If I understood your question right, your trying to get multiple ids and it's associated roles when the user click submit button. You can try the following to get them:
JSP:
<form:form action="approveAccount.html" method="GET">
<input type="submit" value="approvAll"/>
<p>Following Accounts are Pending to approve</p>
<c:forEach items="${accountIdList}" var="val">
<input type="text" value="${val}" name="id">
<select name="role">
<option value="admin">Admin</option>
<option value="user">user</option>
</select>
</c:forEach>
</form:form>
Servlet:
String [] txt = request.getParameterValues("id");
String [] role = request.getParameterValues("role");
for (int i = 0; i < txt.length; i++){
System.out.println(txt[i]+" "+role[i]);
}

How do I submit the right value?

<c:forEach items="${movieList}" var="movie" varStatus="status">
<tr class="<c:if test="${status.count % 2 == 0}">even</c:if>">
<td>${movie.title}</td>
<td>${movie.genre}</td>
<td>${movie.year}</td>
<td>${movie.boxoffice}</td>
<td>
<form:form action=edit.htm>
<input type="hidden" name="edit" value="movie name">
<input type="submit" value="Edit">
</form:form>
<form:form action=delete.htm>
<input type="hidden" name="delete" value="movie name">
<input type="submit" value="Edit">
</form:form>
</tr>
</c:forEach>
This is the section of code I have at the moment. The idea is to display movie data, but also provide buttons to send the user to either a filled form page to edit the data or simply delete the respective data and redirect to the same page. I am just unsure as how to pass along the movie object. I know it is simple, but I can't find the reference I used previously...
Thanks.
U can try this :
put this object in a hidden input
<input type="hidden" id="hidden_object" value="" name="hidden_object"></input>
than you can access the value with the method getParameter()
OR
put this object in your session
in your jsp
<% session.setAttribute("movie", ${movie}); %>
good luck

How to get custom value from text field in JSP?

I'm working in a very simple and small web application, it is a jsp that handles a shopping cart.
What I do at this point is to iterate through all the products that are stored in the car and add them one by one to the jsp with each iteration.
This is the code that adds a row to the jsp in each iteration:
<tr>
<td>
<input type=text name=Quantity value=<%=quantity%>>
</td>
<td>
<input type=text name=id value=<%=id%>>
</td>
<td>
<input type=submit value="Delete" onclick=<%CustomSubmit(request, id); %>>
</td>
</tr>
As you can see I add to the end of each row a submit type control with a custom method for handling Click events, the use of this control is to remove from the car the respective product.
The problem that I have is that when I click in the delete button of a product, the id that is passed to the CustomSubmit(...) method is not the id of the product that I'm trying to remove but the id of the last product added to the jsp.
So, my question is how can I get the correct id from the item that I'm trying to remove?
The way i use to do it is as follows:
Replace
<input type=submit with a button
<input type="button" value="Delete" onclick="deleteIt('yourid');" />
add the deleteIt javascript function, in the function you fill a hidden input field with the id.
Then submit the page and the correct id gets passed to your page
Little sidenote its always prudent to escape all your Strings
dont use <input type=submit but use <input type="submit"
maybe like
<td>
<input type="text" name="id" value="<%=id%>">
</td>
<td>
<input type="button" value="Delete" onclick="deleteItem('<%=id%>')">
</td>
I assume your cart is a list of objects, each having the attributes id and quantity. So I would expect you code to look something like this (noting Peter's answer about using a 'button'):
<input type="button" value="Delete" onclick="CustomSubmit('<%=cartItem.id%>');"/>
I'm not entirely sure what you are trying to do with the 'request' parameter in your original code but if this is the HTTP request all you will get when you try to write it to the JSP is the result of the request.toString method.

Categories