Arraylist from class to array in jsp - java

I am kind of new to JSP. I have got some PHP experience.
I am trying to find a way to store the arraylist data retrieved from a java class file to an array in jsp.
JSP code:
<c:forEach items="${mybean.status}" var="element">
<c:out value="${element}" />
</c:forEach>
Can I store the output retrieved from class file to an array in jsp?
I am looking for something like below. Can this be done with jstl?
String []s = new String[count];
for(int i=0;i<=count;i++) {
s[i] = element ;
}
Thanks in advance.

Sure you can.. even you can store it at once with array.. i did this code using jstl + spring MVC and i got a + button (to add rows) and - button to delete the row (with javascript):
<c:forEach items="${customer.contacts}" varStatus="i">
<tr>
<td><form:hidden path="contacts[${i.index}].id" /> <form:input
path="contacts[${i.index}].desc" type="text" /></td>
<td><form:input path="contacts[${i.index}].number"
type="text" /></td>
<td><button type="button" class="btnbg2" id="del">-</button></td>
</tr>
</c:forEach>
anda when submit it will store all the list in database

Related

How to iterate over a list of object and store data in onclick button in jstl? [duplicate]

This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 1 year ago.
I am extracting and printing a list of studentBean in my jstl page. Along with this also want to create a button beside each extracted object. When user clicks on that he/she gets directed to that sudent profile.
ERROR: On clicking on any of the button I am getting always the last object.
<c:forEach items="${stdBeanList}" var="elements">
<tr>
<td>
<form action="studentList" id="studentListForm">
<c:set var = "rollNum" scope = "session" value = "${elements.rollNum}"/>
<input type="submit" value="view Profile" >
</form>
</td>
<td>${elements.rollNum}</td>
<td>${elements.name}</td>
<td>${elements.grade}</td>
<td>${elements.section}</td>
<td>${elements.gender}</td>
</tr>
</c:forEach>
Try this:
<form action="studentList" id="studentListForm">
<c:forEach items="${stdBeanList}" var="elements" varStatus="loop">
<tr>
<td><input type="checkbox" value="${elements.rollNum}" name="studRollNo"></td>
<td>${elements.rollNum}</td>
<td>${elements.name}</td>
<td>${elements.grade}</td>
<td>${elements.section}</td>
<td>${elements.gender}</td>
</tr>
</c:forEach>
<tr>
<td><input type="submit" value="view Profile"></td>
</tr>
</form>
Servlet:
String rollNo=request.getParameter("studRollNo"); // if multiple values of checkbox nedded then use 'getParameterValues("studRollNo")'
//Your logic to get Student details from Database and store in Object
//set the object in attribute(i.e:Session or request)
//redirect to JSP
//populate the Attribute on JSP suing JSTL

Is there any way to remove an element from array in jsp?

I want to give my users an ability to remove some items from database. Like this:
I have an array in jsp file:
<c:forEach items="${page.content}" var="row" varStatus="status">
<tr>
<td><input type="checkbox"/></td>
<td>${row.name}</td>
<td>${row.profession}</td>
<td>${row.phone}</td>
<td>${row.city.name}</td>
<td><img src="img/del.png"/></td>
Is there any way to remove an item from array "row" (for example, when I click on the picture del.png)? After that, I will send this array to the controller, to let it know which items I want to remove.
So write a if condition inside foreach tag like this.My idea is to exclude or skip the creation of html if if condition is not satisfied with the value you will specify.
<c:forEach items="${page.content}" var="row" varStatus="status">
<c:if test="${row.value != '<What you want to exclude>'}">
<tr>
<td><input type="checkbox"/></td>
<td>${row.name}</td>
<td>${row.phone}</td>
<td>${row.city.name}</td>
</tr>
</c:if>
</c:forEach>

How to show the variable values at the top of the table in jsp?

I am passing an object from servlet to jsp and then I am iterating that object in the jsp and showing the results in a table as shown below. And while iterating the table, I calculate some counts and store it in a variable.
These are my count variable -
kCount
rCount
totalCount
And then I am showing the actual values of these count variables in fieldset as shown below and it works fine.
<div>
<!-- if I try to show the fieldset here, then I see all the values coming as zero. -->
<TABLE>
<TR>
<TH>VALUE1</TH>
<TH>VALUE2</TH>
<TH>VALUE3</TH>
<TH>VALUE4</TH>
</TR>
<c:set var="kCount" value="0" scope="page"/>
<c:set var="rCount" value="0" scope="page"/>
<c:set var="totalCount" value="${CV.getValue().size()}" scope="page"/>
<c:forEach var="i" begin="0" end="${CV.getValue().size() - 1}">
<TR>
<TD>
${CV.getValue().get(i)}
</TD>
<TD>
${CV.getHasR().get(i)}
<c:if test="${CV.getHasR().get(i) == 'True'}">
<c:set var="rCount" value="${rCount + 1}" scope="page"/>
</c:if>
</TD>
<TD>
${CV.getType().get(i)}
<c:if test="${CV.getType().get(i) == 'K'}">
<c:set var="kCount" value="${k + 1}" scope="page"/>
</c:if>
</TD>
</TR>
</c:forEach>
</TABLE>
<!-- I don't want to show the fieldset here, it should be shown at the top of the table -->
<fieldset>
<legend><b>Window</b></legend>
<table>
<tr>
<th>VALUE2</th>
<th>VALUE3</th>
</tr>
<tr>
<td>Total rows:</td>
<td>${totalCount}</td>
</tr>
<tr>
<td>R Count:${rCount}</td>
<td>K count:${kCount}</td>
</tr>
</table>
</fieldset>
</div>
Now If I try to copy this fieldset and try to show at the top of the table instead of showing at the bottom of the table, then I see all the values as zero. My main goal is to show the values of each variables in the fieldset but it should be shown at the top of the table, not at the bottom.
Any thoughts how this can be one if possible at all?
There are at least three options here (I am sure there are many more):
Calculate your totals in the servlet and pass them to the JSP for display
In the JSP, loop through your data first to calculate the totals and display them, then loop again to display the data
In the JSP, loop through and display your data while calculating your totals, then use jQuery or similar to write the totals back into the correct location using javascript.

How to iterate an object in JSP to get the percentage?

I am working on servlet and jsp project. I am passing an object from servlet to JSP. And currently I am iterating that object and showing them in a table -
Below is my code in jsp -
<TABLE id="tableSMS" BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR style="color:#ffffff;background-color:#787878;">
<TH>Hash Name</TH>
<TH>Database Name</TH>
<TH>Version</TH>
</TR>
<c:forEach var="i" begin="0" end="${reportCount.getHash().size() - 1}">
<TR>
<TD>
${reportCount.getHash().get(i)}
</TD>
<TD>
${reportCount.getDatabaseName().get(i)}
</TD>
<TD>
${reportCount.getVersion().get(i)}
</TD>
</TR>
</c:forEach>
And above code is working fine and I am able to show the data properly. Now what I need to do is -
${reportCount.getDatabaseName().get(i)} will return database name as oracle or mysql only. Now I need to calculate what is the percentage of oracle database. I will get the total number of records from ${reportCount.getHash().size(). So if total number of records is 10 and oracle database is present 5 times, then the percentage should be 50%.
Now I am not sure how would I calculate the above percentage using that object? And after calculating that percentage, I need to show the result in a new table which is shown below -
<table>
<tr>
<th style="background-color: #E8E8E6;"><b>Oracle Database</b></th>
</tr>
<tr>
<!-- I would like to show the percentage in this row -->
<td>%</td>
</tr>
</table>
I am thinking I should iterate the reportCount object again in the above new table and extract the percentage here but not sure how would I do that? Can anyone provide an example?
UPDATE:-
Here is my bean code -
public class Response {
private List<String> hash = new LinkedList<String>();
private List<String> databaseName = new LinkedList<String>();
private List<String> version = new LinkedList<String>();
// getters and setters here
}
There are three things as following:
Add the functions taglib:
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Add reportsCounts variable to requestScope instead of session if not required on any other page & use as following:
<c:set var="oracleDBCount" value="0" scope="page" />
<c:forEach var="reportCount"
items="${requestScope.reportCounts.databaseName}" varStatus="loop">
<TR>
<TD>${requestScope.reportCounts.hash[loop.index]}</TD>
<TD>${reportCount}
<c:if test="${reportCount == 'ORACLE'}">
<c:set var="oracleDBCount" value="${oracleDBCount + 1}" scope="page"/>
</c:if>
</TD>
<TD>${requestScope.reportCounts.version[loop.index]}</TD>
</TR>
</c:forEach>
Now display percentage as:
${(oracleDBCount / fn:length(requestScope.reportCounts))*100}%
Based on my experience, doing number-crunching on a JSP page can make it unreadable very quickly. Also you may encounter additional requirements in the future such as:
Text matching (Are you guaranteed that the value is always "oracle"? Or can it become "ORACLE" or "Oracle"?
What if there are zero reports? Then you will need an if-condition to prevent division by zero.
If your client says "We have more report servers like MS, Postgres...can you show the percentage of those?"
Is it possible to do the computation inside the servlet while you are making the reportCount object?
Then you can pass the value inside a session attribute
request.getSession(true).setAttribute("oracleReports", "50%")
and then in the JSP output something like
<c:out value="${sessionScope.oracleReports}"/>
Use JavaScript for doing the operation, Here is the code
Read the comments to understand the code.
Add an id to the so that i can read the inner content using
javascript. Appended id with the index so that each raw gets different
id's
<c:forEach var="i" begin="0" end="${reportCount.getHash().size() - 1}">
<TD id="databaseName<c:out value='${i}' />">
${reportCount.getDatabaseName().get(i)}
</TD>
Add Id to the so that i can set values to the raw using
JavaScript
<tr>
<td id="oraclePercentage">%</td>
<td id="mySQLPercentage">%</td>
</tr>
call the javascript function to set the values to the raw, as we don't
have any button to trigger we open a raw and add the JavaScript call
from the JSP so that the script is triggered every time the page loads
the raw.
<TR><TD><Script>setPercentage('${reportCount.getHash().size() - 1}');</script><TD><TR>
what to do is defined here
<Script>
function setPercentage(var index){
for(var i=0; i<index;i++){
var documentType=document.getElementById("databaseName"+i).innerHTML;
var oracleCount=0;
var mySQLCount=0;
if(vardocumentType=='Oracle')
oracleCount+=(Number)1;
else if(vardocumentType=='MySQL')
mySQLCount+=(Number)1;
document.getElementById("oraclePercentage").innerHTML=(oracleCount/index)*100;
document.getElementById("mySQLPercentage").innerHTML=(mySQLCount/index)*100;
}
</script>

How to use the index variable of a JSTL forEach loop to access a map entry?

With a forEach loop I'd like to create table cells (for a row) whereas each cell contains an input field of a form. The number of table cells is always fixed (12). That is actually no problem. However, here comes the challenge: the forEach should also enter a variable number of default values into the input fields that have to be obtained from a Map(Long, Double).
This is my (simplified) attempt:
<c:forEach var="number" begin="1" end="12" >
<td>
<input type="text" value="${requestScope.aMapWithData[number]}" />
</td>
</c:forEach>
But this doesn't show any value from the Map in the input fields. I guess the problem is that "number" is of type String and not Long. So I wonder if this problem can be solved without using scriptlets.
What number do you want to show? Is it index number of each map entry?
<c:forEach items="${aMapWithData}" var="item" varStatus="status">
<td>
<c:out value="${status.count}."/>
<input type="text" name="${item.key}" value="${item.value}" />
</td>
</c:forEach>
Try this
<c:forEach items="${aMapWithData}" var="mapEntry">
<c:set var="mapKey" value="${mapEntry.key}"></c:set>
<c:set var="mapValue" value="${mapEntry.value}"></c:set>
</c:forEach>

Categories