How to get custom value from text field in JSP? - java

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.

Related

Java- determine which radio button selected

I am dynamically filling a table which contains a radio button in each row. How can I go about determining in which row the radio button has been selected using Java?
<form action='ReceptionManagerController' method='POST'>
<table >
<tr style="text-align:center">
<th>Check-In</th>
<th>Check-Out</th>
<th>Type</th>
<th>Assign Room?</th>
</tr>
<c:forEach var="item" items="${unassignedBookings}">
<tr>
<td>${item.checkIn}</td>
<td>${item.checkOut}</td>
<td>${item.size}</td>
<td><input type="radio" name="checked"></td>
<td><input type="hidden" name="id${count}"></td>
<td><input type="hidden" name="checkIn${count}" value="${item.checkIn}"></td>
<td><input type="hidden" name="checkOut${count}" value="${item.checkOut}"></td>
<td><input type="hidden" name="type${count}" value="${item.size}"></td>
<c:set var="count" value="${count + 1}" scope="page"/>
</tr>
</c:forEach>
</table>
<input type="submit" name="action" value="Assign Booking"/>
</form>
If I give each radio button the same name, then only one can be selected at a time. However, this stops me from determining uniquely which button has been pressed.
Any suggestions?
Thank you for your help.
I had a similar problem last year while working on a struts 1.3 based web application. You can refer to the this link. I hope it will help you. If still its not clear to you, let me put some try on it.
You can take an ArrayList of your bean type(Using Generics) having the setter and getter for it and keep the appropriate values for all the bean objects and add all those objects one by one in your ArrayList. After that iterate the ArrayList in your JSP to display the properties along with radio button. Rest of all is explained in given link.
Note: Your bean class must have a property with proper getter/setter for the radio button.
By the form that I can see, Check-Box seems to be appropriate choice rather than Radio Button. As far as capturing the selection is concerned, you can follow same strategy that you are doing for rest of the form elements, suffix count value to radio-Button or check-box to give them uniqueness.

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

How to edit fields of a table?

I have a table to show a long list of items, I am wondering how I can edit the fields and submit the form to update them?
<form name="edit" method="POST" action="edit">
<table border="4">
<tbody>
<c:forEach items="${basket.items}" var="item">
<tr>
<td>
<input name="item.id" value="${item.id}"/>
</td>
<td>
<input label="Price" value="${item.product.price}"/>
<br/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
this is a new one
<input id="edit" type="submit" name="edit" value="Edit"/>
</form>
You are using Struts2, with JSTL and EL instead of Struts Tags and OGNL... is there a particular reason that forces you to drop most of the framework mechanics ?
That said, your inputs aren't valid (no type specified) and the "this is a new one" sentence in the HTML seems to indicate the willing to insert a new row, instead of editing the existing entres. Your description and your code seem to ask two different things... to insert a new one, just make a call to another method of the action (or another action) called "add" instead of "edit", sending one single element and adding it to the collection. No need to use AJAX here...
If instead, the question is really:
how I can edit the fields and submit the form to update them ?
this is the way:
<s:form method="POST" action="edit">
<table border="4">
<tbody>
<s:iterator value="basket.items" var="item" status="ctr">
<tr>
<td>
<s:textfield name="item[%{#ctr.index}].id" />
</td>
<td>
<s:textfield name="item[%{#ctr.index}].product.price" />
</td>
</tr>
</s:iterator>
</tbody>
</table>
<s:submit value="Edit"/>
</form>
I would suggest you make an AJAX call using jquery to update the new one. And then in the success handler you can append the new line to the existing table. Before doing that you need to give your table proper ids so that its easier to use JQUERY.
var newLine = document.createElement("tr");
var cellName = document.createElement("td");
$(cellName).text("itemId");
$(newLine).append(cellName);
// similarly create other td's
$("#modelTable").append(newLine);// replace modelTable by the id of your table

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

Sending form parameters from JSP to Struts action class

I am implementing a search functionality in a website I am building, which involves searching by the md5 hash of the name of the file submitted and searching by the notes associated with each submitted file. So, I should detect as to which button is pressed "Search by MD5" or "Search by Notes". This is the code I have:
JSP code for the form:
<form id="search" name="search" action = "search.do"
method="POST" enctype="multipart/form-data">
<table align = "center">
<tr>
<th colspan="4" bgcolor="#004276"><font color="white">
Search for Sample
</th>
</tr>
<tr>
<td><input name="md5" type="text" value="${form.md5}"/></td>
<td><input name="md5search" type="submit" value="Search by MD5"/>
</tr>
<tr>
<td><input name="notes" type="text" value="${form.notes}"/></td>
<td><input name="notessearch" type="submit" value="Search by Notes"/>
</tr>
</table>
</form>
search.do is mapped to SearchResultsAction.java. Code in Java action class (SearchResultsAction) which handles the request is:
if(request.getParameter("md5search").toString().equals("Search by MD5")){
searchSubmissionsList = submissionsDAO.searchSubmissionsByMD5(form.getMD5());
}
if(request.getParameter("notessearch").toString().equals("Search by Notes")){
searchSubmissionsList = submissionsDAO.searchSubmissionByNotes(form.getNotes());
}
But the problem I am facing here is that, request.getParameter("md5search") and request.getParameter("notessearch") return null for some reason. I have been working on this for a while and have not been able to figure it out. The weird thing is that it once worked for me sometime back when I was working on another project. Am I missing something here?
It's null because you used multipart/form-data form encoding instead of (default) application/x-www-form-urlencoded. Basically, you have to (let Struts) extract the text fields from the multipart form data body the same way as you (or Struts) extracted the uploaded file. Or, as there is actually no <input type="file"> field in your form at all, just remove the enctype attribute altogether.
See also
Does form with enctype="multipart/form-data" cause problems accessing a hidden field

Categories