<%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">
Related
I have a foreach value in an iteration in a jsp page as shown
<c:forEach var="lists" items="${lists}" varStatus="theCount">
String val= ${lists.getVal() } ; //this is giving me error
</c:forEach>
https://www.tutorialspoint.com/jsp/jstl_core_set_tag.htm
<c:forEach var="list" items="${lists}" varStatus="theCount">
<c:set var="val" value="${list.val}"/>
<p>The value is: ${val}.</p>
</c:forEach>
how to change the scriplet to JSTL
<%String sentenceArray[] = (String[])request.getAttribute("displaySentenceArray"); %>
<% for (int i=0; i< sentenceArray.length;i++){ %>
<p> The Result IS : <%=sentenceArray[i] %> </p>
<%} %>
I am new to JSTL
Your JSTL should look like this
<c:forEach var="sentence" items="${requestScope.displaySentenceArray}" >
<p> The Result IS :<c:out value="${sentence}"></c:out></p>
</c:forEach>
Here requestScope.displaySentenceArray will get the whole array from request.'sentence'will be a single element of array, <c:forEach> tag will iterate the array and <c:out> will print the element to JSP.
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>
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 want to change all scriptlets in my jsp pages to jstl,
how can i change this code to jstl
<% Map validationResults = (HashMap) request.getAttribute("validationResults");%>
<% if (validationResults != null) {
if (validationResults.containsKey("userName")) { //how can i chage this line to jstl ?
%>
<%=((ValidationResult) (validationResults.get("userName"))).getDetails()%> //how can i chage this line to jstl too ?
<%}%>
<%}%>
MY JSTL
<c:set var="validationResults" value="validationResults" scope="request"></c:set>
<c:if test="validationResults != null">
//how can i change the code of map here?
</c:if>
and another problem with ArrayList which contains list of Group object , in the loop i want to get each Group object and check a specific method inside Group object , how can I reach to these method through jstl??
I want to change this code
<%List<Group> allGroupList = new ArrayList<Group>();
allGroupList = (ArrayList) request.getAttribute("groups");%>
<% for (int index = 0; index < allGroupList.size(); index++) {%>
<%Group aGroup = (Group) allGroupList.get(index);%>
<label ><%=aGroup.getGroupEName()%></label>
<%if (aGroup.isIsUserGroup()) {%>
<input type="checkbox" name="group" value="<%=aGroup.getGroupNo()%>" CHECKED />
<%} else {%>
<input type="checkbox" name="group" value="<%=aGroup.getGroupNo()%>" />
<%}%>
<%}%>
here's my changed code:
<jsp:useBean id="GroupBean" class="ps.iugaza.onlineinfosys.entities.Group" type="ps.iugaza.onlineinfosys.entities.Group" scope="reqeust">
<c:set var="allGroupList" value="groups" scope="request"></c:set>
<c:forEach var="grp" items="${allGroupList}" varStatus="status">
//?????? what should i do ?
</c:forEach>
For The First Part
JSTL and EL only work with method that follows Java Bean convention. If you really wanna go this route, then you can loop around your map.
<c:forEach items="${requestScope.validationResults}" var="mapEntry" varStatus="index">
<c:if test="${mapEntry.key == 'userName'}">
<tr>
<td>${mapEntry.value.details}</td>
</tr>
</c:if>
</c:forEach>
The other way can be just get userName from the map, and check for if its null or not, and then do whatever you like. This is indeed a better idea.
<c:if test="${requestScope.validationResults['userName'] != null}">
<tr>
<td>${requestScope.validationResults['userName'].details}</td>
</tr>
</c:if>
For The Second
<c:forEach var="grp" items="${requestScope.groups}" varStatus="status">
<label>${grp.groupEName}</label>
<input type="checkbox" name="group" value="${grp.groupNo}" ${grp.isUserGroup ? 'checked' : ''} />
</c:forEach>
As for no 1), You would have to populate your request through an action/controller, and have a JSTL script that iterates through your map as follows:
Warning: Untested
<c:if test="${requestScope.validationResults != null}">
<c:forEach var="entry" items="${requestScope.validationResults}">
<c:if test="${entry.key == 'userName'}">
Result: ${entry.value.details};
</c:if>
</c:forEach>
</c:if>
Adeel Ansari answered number 2 for you.