In jsp i have this portion and works fine
<c:forEach var="info" items="${infoList}" >
<tr>
<td>${info.key} </td>
<td>${info.total}</td>
<td>${info.delay}</td>
</tr>
</c:forEach>
here infoList comes from struts action class which is a ArrayList of Class Info
public class Info{
private String key;
private String total;
private String delay
}
Now i need to add another <td> which will print the percentage calculated like ${info.delay}*100/${info.total} but will print exactly two digit after decimal.
I tried this
${ info.totalDelay*100/info.totalShipment }
which print the percentage but can't limit to 2 digit. In java i can use
NumberFormat formatter = new DecimalFormat("#0.00");
But how i will do that i here because in in <% %> (jap tag) i cant use ${}
Can i access those variable in <% %> some how Or can i use formatter .format() in a <c:> tag
Using JSTL Format Number
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatNumber type="number" minFractionDigits="2" maxFractionDigits="2" value="${ info.totalDelay*100/info.totalShipment } " />
Well i figured it out
in the top i did this :
<%
NumberFormat numberFormat=new DecimalFormat("#.##");
%>
And i the td i did this:
<td>
<c:set var="tl" value="${info.total}"></c:set>
<c:set var="dl" value="${info.delay}"></c:set>
<jsp:useBean id="tl" class="java.lang.String"/>
<jsp:useBean id="dl" class="java.lang.String"/>
<%
out.println(numberFormat.format(Double.parseDouble(dl)*100/Integer.parseInt(tl)));
%>
</td>
Related
<%#page import="java.util.List"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<%# page import="java.sql.*" %>
<%# page import= "myExam.quest" %>
</head>
<body>
<%! int index=0; %>
<%! int pos=0; %>
<% String c,a;
String[] CA =(String[])session.getAttribute("CA");
String[] AS =(String[])session.getAttribute("AS");
List<quest> l=(List<quest>)session.getAttribute("myquestion");
quest[] question = new quest[l.size()];
l.toArray(question);
%>
<table border=1>
<tr>
<th colspan="2" width="500">Questions</th>
<th>CorrectAnswer</th>
<th>Answer sheet</th>
</tr>
<tr>
<%
for(pos=0;pos<question.length;pos++){
String ques=question[pos].ques;
String opa=question[pos].opa;
String opb=question[pos].opb;
String opc=question[pos].opc;
String opd=question[pos].opd;
c=CA[pos];
a=AS[pos];
%>
<td>Question <%=pos+1%></td>
<td width="500"><%= ques %></td>
<td><%=c %></td>
<td><%= a%>
</tr>
</table>
<%} %>
</body>
</html>
I had written every thing is write please ignored the session
the output come is
output of the program
only the first line comes in the table format
please suggest some work to perform or how to modify it
It is a very bad practice to write code using scriplets. You should avoid using scriplets. Anywayas, try with below code:
Insert title here
<% String c,a;
String[] CA =(String[])session.getAttribute("CA");
String[] AS =(String[])session.getAttribute("AS");
List<quest> l=(List<quest>)session.getAttribute("myquestion");
quest[] question = new quest[l.size()];
l.toArray(question);
%>
<table border=1>
<tr>
<th colspan="2" width="500">Questions</th>
<th>CorrectAnswer</th>
<th>Answer sheet</th>
</tr>
<%
for(pos=0;pos<question.length;pos++){
String ques=question[pos].ques;
String opa=question[pos].opa;
String opb=question[pos].opb;
String opc=question[pos].opc;
String opd=question[pos].opd;
c=CA[pos];
a=AS[pos];
%>
<tr><!-- moved tr inside for loop-->
<td>Question <%=pos+1%></td>
<td width="500"><%= ques %></td>
<td><%=c %></td>
<td><%= a%></td><!-- added missing /td-->
</tr>
<%} %>
</table><!-- moved /table outside of for loop-->
</body>
Problem is your table html is not well nested within the loop.
<%
for(pos=0;pos<question.length;pos++){
String ques=question[pos].ques;
String opa=question[pos].opa;
String opb=question[pos].opb;
String opc=question[pos].opc;
String opd=question[pos].opd;
c=CA[pos];
a=AS[pos];
%>
<tr> <!-- moved inside -->
<td>Question <%=pos+1%></td>
<td width="500"><%=ques%></td>
<td><%=c%></td>
<td><%=a%></td> <!-- added missing closing tag -->
</tr>
<%} %>
</table><!-- moved outside -->
P.S. Also consider using JSTL Core tags for such kind of implementation.
<%for(int i = 1; i < pl.getNoOfSegments(); i++){
%>
<list:column column="segment<c:out value="${i}"/>_value" titleKey="${pickList.pickListSegment.segment1Label}" searchType="input" type="nstring"/>
<%
}
%>
Here in the above scenario I want to populate the value of the column and titleKey but I am unable to use the ${i} EL and it doesn't giving any terminated error. For titleKey the segment1Label ie 1 I want to replace with I value but not able to do so?
I'm new to EL/scriplets as well so this might not be the best way to do it.
What you can do is define a var and increment it manually so it would have the same value as i.
<c:set var="count" value="1" scope="page" /> //define your variable here
<%
for(int i=1;i<pl.getNoOfSegments();i++){
%>
<c:out value="${count} test"/> // ${count} here has the same value as i
<c:set var="count" value="${count + 1}" scope="page" /> //increment count
<%
}
%>
Alternatively, instead of using Scriptlets, you could look into using JSTL tags such as:
<c:forEach begin="1" end="${passedAttr}" varStatus="loop">
I've a JSP, where I display elements through JSTL c:forEach loop. This is a nested loop as shown below:
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
**Element rows displayed here**
Now, when the user selects any of the element row in the inner most loop, I've to fetch the values in JS. As you can see I'm trying to get the count of each nested loop like this:
<input type="hidden" name="tierOneIndex" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" value="${budgetItemCount.count}">
And trying to fetch the value of input field in JS as below:
var tierOneIndex = $('input[name="tierOneIndex"]').val();
var tierTwoIndex = $('input[name="tierTwoIndex"]').val();
var budgetItemIndex = $('input[name="budgetItemIndex"]').val();
But whatever element I select, I'm always getting:
tierOneIndex = 0
tierTwoIndex = 0
budgetItemIndex = 0
Any ideas how I can fetch the count values.
In your html you can do like this
<table>
<c:forEach items="${auditBudgetData.auditBudgetTierOneList}" var="auditBudgetTierOne" varStatus="tierOneCount">
** Some Code **
<c:forEach items="${auditBudgetTierOne.auditBudgetTierTwoList}" var="auditBudgetTierTwo" varStatus="tierTwoCount">
** Some Code **
<c:forEach items="${auditBudgetTierTwo.auditBudgetItemList}" var="auditBudgetItem" varStatus="budgetItemCount">
<input type="hidden" name="tierOneIndex" id="tierOneIndex_${budgetItemCount.index}" value="${tierOneCount.count}">
<input type="hidden" name="tierTwoIndex" id="tierTwoIndex_${budgetItemCount.index}" value="${tierTwoCount.count}">
<input type="hidden" name="budgetItemIndex" id ="budgetItemIndex_${budgetItemCount.index}" value="${budgetItemCount.count}">
<tr class="rows" id="${budgetItemCount.index}"><td>click Here</td></tr>
</table>
and in javascript you can do like this
$(document).ready(function(){
$("tr.rows").click(function() {
var rowid=this.id;
var tierOneIndex = $('#tierOneIndex_'+rowid).val();
var tierTwoIndex = $('#tierTwoIndex_'+rowid).val();
var budgetItemIndex = $('#budgetItemIndex_'+rowid).val();
console.log("tierOneIndex:"+tierOneIndex);
console.log("tierTwoIndex:"+tierTwoIndex);
console.log("budgetItemIndex:"+budgetItemIndex);
});
});
Note:
${tierOneCount.index} starts counting at 0
${tierOneCount.count} starts counting at 1
i created one sample fiddle also for you
http://jsfiddle.net/9CHEb/33/
Similar Approach
You will find an approach in this StackOverflow Q&A link.
Solution
In detail, I would go for something like this (JSP)
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<script src="/*link to jQuery*/"></script>
<script>
$(document).ready(function() {
$("td").click(function(event) {
var dtoItemIdx = $(this).attr("data");
//alert("Selected idx: " + dtoItemIdx);
console.info("Selected idx: " + dtoItemIdx);
});
});
</script>
<%-- Get the size of collection --%>
<c:set var="size" scope="page" value="${fn:length(dto.items)}" />
<c:out value="There are ${size} elements in the list." />
<table>
<c:forEach items="${dto.items}" var="item" varStatus="row">
<tr><td data="${row.index}">
<%-- Get the current index in the loop --%>
<c:out value="Your content i.e [row idx: ${row.index}]." />
</td></tr>
</c:forEach>
</table>
Extensions
Instead of only one loop you can obviously nest several loops. The different index could be stored in a CSV-like structrue:
...<td data="${row.index};${product.index};${properties.index}">...
Please leave a comment if this does not solve your problem.
I am developing web application.In jsp page I am iterating a list using Scriptlets tags. But I want to execute the same result in JSTL. How Can I do?
Here list contain Column names of Data Base.
Here eList contain Table data (values of a table)
Below is My JSP code:
<table border="1" cellpadding="5" cellspacing="5">
<tbody>
<tr>
<th>SNO</th>
<c:forEach var="column" items="${list}">
<th> ${column} </th>
</c:forEach>
</tr>
//For above list JSTL exectude successfully but while doing below list is not possible
<%List eList =(Vector)request.getAttribute("list1");
Integer s1 = (Integer) request.getAttribute("sno");
Iterator it = eList.iterator();
while (it.hasNext()) {
%>
<tr> <td><%=++s1%></td><%
Object[] row = (Object[]) it.next();
for (int k = 0; k < row.length; k++) {
%>
<td> <%=row[k]%></td>
<% }%>
</tr>
<%
}
%>
</tbody>
</table>
Servelt code
GetTableData .java:
public class GetTableData extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
Query query1 = entityManager.createNativeQuery("select * from "
+ schemaName + "." + tableName + "");
totalNumberOfRecords = query1.getResultList().size();
query1.setFirstResult(newPageIndex);
query1.setMaxResults(numberOfRecordsPerPage);
List list1 = query1.getResultList();
System.out.println("testszenario" + testszenario.size());
System.out.println(testszenario);
request.setAttribute("list1", list1);
request.getRequestDispatcher("/TableResult.jsp").forward(request,
response);
}
}
How can I do that one with JSTL tags.Thanking you very much
The list1 is in request scope so you can just iterate as you did, for printing SR.No. you can make use of LoopTagStatus
<c:forEach var="data" items="${list1}" varStatus="loop">
<td> ${loop.count} </td>
<td> ${data} </td>
</c:forEach>
Remember
${loop.index} starts from 0
${loop.count} starts from 1
See also
JSTL core
How to avoid Java Code in JSP-Files?
Do like Below
<c:forEach var="data" items="${list1}" varStatus="loop">
<tr>
<td> ${sno+1} </td>
<c:forEach var="innerData" items="${data}">
<td> ${innerData} </td>
</c:forEach>
<c:set var="sno" value="${sno+1}"/>
</tr>
</c:forEach>
Include a jstl jar and include them in jsp page like shown below
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>.............
then by using
<c:forEach items="${values that are set in any scope}" var="any variable">......
..
Please refer to below code.
<c:forEach var="data" items="${list1}" varStatus="loop">
<tr>
<td> ${loop.count} </td>
<c:forEach var="innerData" items="${data}">
<td> ${innerData} </td>
</c:forEach>
</tr>
</c:forEach>
I am creating small web apps and I am facing the following problem. I have 2 JSPs and when I click the submit button, it repeats the value every time. What I want is that when I click on the submit button it should give only the corresponding value.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.io.*,java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Class Video</title>
</head>
<body>
<form action="second.jsp" method="post">
<table>
<%
File f=new File("C:/Users/SHAKTI/Desktop/video");
File[] list=f.listFiles();
if(list.length!=0){
String s[]=new String[list.length];
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
%>
<tr><td><%=fi %></td>
<td><input type="text" name="file" value="<%=s[i] %>">
</td>
<td><input type="submit" name="play" value="Play"></td>
</tr>
<%}}
else{
%>
<tr>
<td>There is no any files in the database...</td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
second.jsp
<form action="" method="post">
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
String id=request.getParameter("file");
out.println("id = "+id);
%>
<input type="submit" name="submit" value="submit>
</form>
First Jsp : Set Value in First Page
request.setAttribute("name",somevalue);
Second Jsp : Retrieve it in Second page
request.getAttribute("name")
use queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;
One way is to use session as described by javaBeginner.
you can also create a from on the fly and submit it.
write a function similar to this one and use it in your success:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}
There are many options to pass a value from one jsp to another, Here are some
1) Adding that as a hidden variable and specifying the value
<input name="file" type="hidden" value=""/>
2)Adding it to the session and retrieving the session variable
session.setAttribute("file", value);
3)Passing that as a queryParameter
http://......one.jsp?file=""
It is beacause you are iterating the loop here,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
so it will print the last element from the loop, to get the name u clicked on the button try this .. Change this line as
<input type="text" name="file" value="<%=s[i] %>">
as,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
And handle it using jQuery like this , so that you can pass the value to next JSP,
<script type="text/javascript">
$(document).ready(function () {
$(".btn").click(
function() {
var selectedFileName = $(this).attr("data-reqno");
var urlToApprove = "/yourApp/req/filename?name=" + selectedFileName;
}
);
});
</script>
And also try to avoid Scriptlets in JSP , you can use JSTL or El for the same purpose .
Hope it helps !!
there are many method to pass variable such as
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"