<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]);
}
Related
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
I need to create a jsp page to edit data from an oracle database.
I thought that the easiest thing I could do was to create a combobox showing important info
(in this case: id+ name of the material) but I have problems filling the text fields.
My idea is to fill those fields after the text on the combobox changes, but I don't really know how to do it. I know that with the info of the combobox, I have to do a query to obtain the data and then recall the jsp or something, but I don't exactly if I have to call a Servlet or what is the best way to do it.
Sorry if this question is repeated, but I didn't find any posts helpful.
Some code:
<sql:setDataSource dataSource="bd/login"/>
<sql:transaction>
<%--Vamos a hacer una consulta a la bd--%>
<sql:query var="resultado">
select * from material order by codigo
</sql:query>
</sql:transaction>
<form name="formActualizar" action="../ServletActualizarDatos" method="POST">
<select name="select" styleId = "tempId" onchange="ActualizarDatos()">
<option selected="selected"> -- Elija material --</option>
<c:forEach var="material" items="${resultado.rows}">
<option value="${material.codigo}">${material.codigo} ${material.nombre}</option>
</c:forEach>
</select><br/><br/>
Código<br/>
<input type="text" name="codigo" value="" /></p>
Nombre<br/>
<input type="text" name="nombre" value=""/></p>
Resistencia<br/>
<input type="text" name="resistencia" value="" /></p>
<input type="submit" name="bt" value="Actualizar Material" />
</form>
<script>
function ActualizarDatos()
{
String texto = this.options[this.selectedIndex].text;
Material m = ServletActualizarDatos.ObtainMaterialFromCombo(text);
this.form['codigo'].value=String.valueOf(m.getCodigo());
this.form['nombre'].value=m.getNombre();
this.form['resistencia'].value=String.valueOf(m.getResistencia());
}
</script>
Thank you for your help.
///CODE UPDATED, DOESN'T SEEMS TO WORK YET, THE EVENT IS NOT CALLED
You need jvascript to handle event when select box change to set the values of input fields from this select box selected value and selected option.
<select name="select" styleId = "tempId" onchange="this.form['codigo'].value=this.value;this.form['nombre'].value=this.options[this.selectedIndex].text;">
I am passing a list inside a session from servlet to a jsp as follows :
HttpSession session = req.getSession();
session.setAttribute("list1", arrayList);
Inside the JSP I am printing the list as follows :
<form action="Save" method="post">
<c:forEach items="${list1}" var="item">
${item}<br>
<c:set var="stringArray" value="${fn:split(item, ',')}" />
<input type="text" name="Deivice" value="${stringArray[0]}" />
<input type="text" name="DTA" value="${stringArray[1]}" />
<input type="text" name="Type" value="${stringArray[2]}" />
<br>
</c:forEach>
<input type="submit" value="Save">
</form>
Now I want to retrieve the list in a servlet (after the user modifies it in the UI)
How can I pass the values back to the servlet ? Basically, I want to pass a list,alow the user to modify the contents of the list on the UI and want the modified contents of the list in a servlet.
Simply submit the form and get the values in Servelt using request.getParameterMap() or request.getParameterValues(String) that returns String[] for each parameter name that is submitted.
For e.g
String[] devices = request.getParameterValues("Deivice");
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" />
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.