I want to avoid multi loop in JSTL which is shown by the code presented below. I got attributes WRTSC, DTA, DTA_PRZEDST_TR_OSW from api response and they are passing randomly so that is why the code looks like this.
<c:forEach items="${ctx.model.customerAttributes}" var="customerAttribute">
<tr>
<td class="code">${customerAttribute.subGroupName}</td>
<td class="value">
<c:forEach items="${customerAttribute.attributes}" var="attribute">
${attribute.attrName == 'WRTSC' ? attribute.attrValue : ''}
</c:forEach>
</td>
<td class="value">
<c:forEach items="${customerAttribute.attributes}" var="attribute">
${attribute.attrName == 'DTA' ? attribute.attrValue : ''}
</c:forEach>
</td>
<td class="value">
<c:forEach items="${customerAttribute.attributes}" var="attribute">
${attribute.attrName == 'DTA_PRZEDST_TR_OSW' ? attribute.attrValue : ''}
</c:forEach>
</td>
</tr>
</c:forEach>
I need to read every attribute (if there is not attribute sent I need to create empty <td></td> block.
Can it be done in one loop instead of three (in this case this number respresents the number of different attributes).
Thanks for helping.
I've got something like this now. Guys, do you think this is better?
<c:forEach items="${ctx.model.customerAttributes}" var="customerAttribute">
<tr>
<c:set var="WRTSC" value="" />
<c:set var="DTA" value="" />
<c:set var="DTA_PRZEDST_TR_OSW" value="" />
<c:forEach items="${customerAttribute.attributes}" var="attribute">
<c:if test="${WRTSC eq ''}">
<c:set var="WRTSC" value="${attribute.attrName == 'WRTSC' ? attribute.attrValue : ''}" />
</c:if>
<c:if test="${DTA eq ''}">
<c:set var="DTA" value="${attribute.attrName == 'DTA' ? attribute.attrValue : ''}" />
</c:if>
<c:if test="${DTA_PRZEDST_TR_OSW eq ''}">
<c:set var="DTA_PRZEDST_TR_OSW" value="${attribute.attrName == 'DTA_PRZEDST_TR_OSW' ? attribute.attrValue : ''}" />
</c:if>
</c:forEach>
<td class="code">${customerAttribute.subGroupName}</td>
<td class="value">${WRTSC}</td>
<td class="value">${DTA}</td>
<td class="value">${DTA_PRZEDST_TR_OSW}</td>
</tr>
</c:forEach>
You can use something like this
<c:forEach items="${ctx.model.customerAttributes}" var="customerAttribute">
<tr>
<td class="code">${customerAttribute.subGroupName}</td>
<td class="value">
<c:forEach items="${customerAttribute.attributes}" var="attribute">
${(attribute.attrName == 'WRTSC') || (attribute.attrName == 'DTA') || (attribute.attrName == 'DTA_PRZEDST_TR_OSW')? attribute.attrValue : ''}
</c:forEach>
</td>
</tr>
</c:forEach>
or
<c:forEach items="${ctx.model.customerAttributes}" var="customerAttribute">
<tr>
<td class="code">${customerAttribute.subGroupName}</td>
<td class="value">
<c:forEach items="${customerAttribute.attributes}" var="attribute">
<c:if test="${(attribute.attrName == 'WRTSC') || (attribute.attrName == 'DTA') || (attribute.attrName == 'DTA_PRZEDST_TR_OSW')}">
${attribute.attrValue}
</c:if>
</c:forEach>
</td>
</tr>
</c:forEach>
Rather than running 3 inner loop take 3 inner variable for
var WRTSC='';
var DTA ='';
var DTA_PRZEDST_TR_OSW ='';
and run only one inner loop in which check the condition with the variables , if condition is match set the value of variable otherwise by default value is '' .
Related
I have one jsp page. I am passing 2 model objects from spring controller.
asset (gets selected asset).
assets (get all assets)
I want to set option selected if condition matches.
My code
<table>
<tr>
<td>Asset Id :</td>
<td>
<form id="getAssetForm" method="get">
<select id="assetid" name="assetid" onchange="submitForm(this);">
<c:if test="${not empty assets}">
<c:forEach items="${assets}" var="assetsproperties">
<c:choose>
<c:when test="${not empty asset}">
<c:forEach items="${asset}" var="assetobj">
<c:choose>
<c:when test="${assetobj.id} == ${assetsproperties.id}">
<option value="${assetobj.id}" selected>${assetobj.name}</option>
</c:when>
<c:otherwise>
<option value="${assetsproperties.id}">${assetsproperties.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</c:when>
<c:otherwise>
<option value="${assetsproperties.id}">${assetsproperties.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</c:if>
</select>
</form>
</td>
</tr>
<tr>
<td>Name :</td>
<td><input type="text" name="assetname" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.name}</c:forEach></c:if>"></td>
</tr>
<tr>
<td>Model Number :</td>
<td><input type="text" name="assetmodelnumber" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.modelNumber}</c:forEach></c:if>"></td>
</tr>
<tr>
<td>Rating (1 to 5 ):</td>
<td><input type="text" name="assetrating" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.rating}</c:forEach></c:if>"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="Save" value="Update">
</tr>
</table>
<script type="text/javascript">
function submitForm(a){
var e = document.getElementById("assetid");
var assetid = e.options[e.selectedIndex].value;
var assetnametxt = e.options[e.selectedIndex].text;
var assetnameElement = document.createElement("input");
assetnameElement.type = "hidden";
assetnameElement.name = "assetname";
assetnameElement.value = assetnametxt;
var form = document.getElementById('getAssetForm');
form.appendChild(assetnameElement);
form.setAttribute('action', "get-asset");
form.submit();
}
</script>
here is my controller code :
#RequestMapping(value="/get-asset", method = RequestMethod.GET)
public String showGetAssetPage(ModelMap model,
#RequestParam("assetid") int assetid,
#RequestParam("assetname") String assetname){
System.out.println("inside showGetAssetPage() ");
List<Asset> asset = service.getAsset(assetid, assetname);
model.addAttribute("asset", asset);
List<Asset> assets = service.getAssets();
model.addAttribute("assets", assets);
return "update-asset";
}
I want to show selected asset on page load.
How to match condition using jstl?
You should have a boolean field isSelected in your Asset model. In your controller,set the isSelected property in all the assets object. Using this only all assets and checking isSelected property you can set is as selected.
I'm having a few problems with some JSTL code. The thing is that i'm trying to compare the id of the user that logged in with the id from the reservation class which has a foreign key of the user id.And after doing that i'm trying to populate the page with update links based on the reservation id.
Here's the code of what i tried but i can't find a way to make it work.
<table>
<tr>
<th>Reservation Id</th>
<th>Data CheckIn</th>
<th>Data CheckOut</th>
<th>Numar Persoane</th>
<th>Numar Camere</th>
<th>Action</th>
<%
List<ReservationBean> theReserv = (List<ReservationBean>) request.getAttribute("RESERVATION_LIST");
%>
<% int userId = (Integer) request.getSession().getAttribute("userId"); %>
<c:forEach var="tempReservation" items="${RESERVATION_LIST}">
<!-- set up a link for each res -->
<c:url var="tempLink" value="UserControllerServlet">
<c:param name="command" value="LOAD"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<c:url var="deleteLink" value="UserControllerServlet">
<c:param name="command" value="DELETE"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
</c:forEach>
<% for(ReservationBean res : theReserv){
/* int userId = (Integer) request.getSession().getAttribute("userId"); */
if(userId == res.getUserId()){ %>
<tr>
<td> <%= res.getReservationId() %> </td>
<td> <%= res.getDataCheckin() %> </td>
<td> <%= res.getDataCheckout() %> </td>
<td> <%= res.getNrPersoane()%> </td>
<td> <%= res.getNrCamere() %> </td>
<td>Update
|
<a href="${deleteLink}"
onclick="if(!(confirm('Are you sure you want to delete this reservation?'))) return false">Delete</a>
</td>
</tr>
<%}%>
<%}%>
</tr>
</table>
In the second for i'm comparing the id of the user that logged in with the id of the user from the reservation class but of course the updated links will contain the last value of the first for and i don't know how to do what i did in pure java with JSTL to have only one for and get the correct values of the update link or delete ones.Do you guys have any clue on how to do that?
I've tried something like this
<table>
<tr>
<th>Reservation Id</th>
<th>Data CheckIn</th>
<th>Data CheckOut</th>
<th>Numar Persoane</th>
<th>Numar Camere</th>
<th>Action</th>
<%
List<ReservationBean> theReserv = (List<ReservationBean>) request.getAttribute("RESERVATION_LIST");
%>
<% int userId = (Integer) request.getSession().getAttribute("userId"); %>
<c:forEach var="tempReservation" items="${RESERVATION_LIST}">
<!-- set up a link for each res -->
<c:if test="${tempReservation.userId}" == userId >
<c:url var="tempLink" value="UserControllerServlet">
<c:param name="command" value="LOAD"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<c:url var="deleteLink" value="UserControllerServlet">
<c:param name="command" value="DELETE"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<tr>
<td>${tempReservation.reservationId}</td>
<td>${tempReservation.dataCheckin}</td>
<td>${tempReservation.dataCheckout}</td>
<td>${tempReservation.nrPersoane}</td>
<td>${tempReservation.nrCamere}</td>
<td>Update
|
<a href="${deleteLink}"
onclick="if(!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:if>
</c:forEach>
But that if condition doesn't work or i don't know how to compare jstl code with java code
Edit2: I made it work! You had to compare it something like this
<c:if test="${tempReservation.userId == userId }">
Thanks for help!
I have a form with some inputs; each input returns a list of data which is displayed in a table in another html page. Each input have a table to display it's data. My task is to do not display the data if the input is not entered by the user.
Here is my code
<!-- Country Table-->
<%for(int i = 0; i < countryList.length;i++){
if(countryList.length == 0)
break;
%>
<div class="box" align="center">
<table name="tab" align="center" class="gridtable">
<thead >
<tr>
<th style="width: 50%" scope="col">Entity Watch List Key</th>
<th style="width: 50%" scope="col">Watch List Name</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width: 50%"><%out.println((String) (countryList[i].getEntityWatchListKey()));%></td>
<td style="width: 50%"><%out.println((String) (countryList[i].getEntityName()));%></td>
</tr>
</tbody>
</table>
</div>
<%}%>
I am using break to go out of the loop to do not display the table, is that true ?
You can use this condition before the for loop,
if(countryList.length != 0)
or
if(countryList.length > 0)
and then you need not use the break condition,
Furthermore the for loop you have currently defined will not work because if the length of the array is 0 then this condition i < countryList.length will become 0<0 and it will fail,so your for loop won't even be entered.So your current if condition if(countryList.length == 0) will not be accessed.
Please modify your code
<div class="box" align="center">
<table name="tab" align="center" class="gridtable">
<thead >
<tr>
<th style="width: 50%" scope="col">Entity Watch List Key</th>
<th style="width: 50%" scope="col">Watch List Name</th>
</tr>
</thead>
<tbody>
<%for(int i = 0; i < countryList.length;i++){
if(countryList.length > 0) %>
<tr>
<td style="width: 50%"><%out.println((String) (countryList[i].getEntityWatchListKey()));%></td>
<td style="width: 50%"><%out.println((String) (countryList[i].getEntityName()));%></td>
</tr>
<%}%>
</tbody>
</table>
</div>
For a good practice you have to repeat the row not the table.
I need to pass values from one jsp to another jsp and then the values are processed in that another jsp and then that jsp will be included in first jsp.
The jsp variables which I need to pass are from Comp_Mps_hs.jsp to Comp_Mps_hs_diff.jsp are
<jsp:useBean id="ref" class="comp_Mps.Comp_Mps_hs"/>
<br>
<%
//Comaprision obj = new Comaprision();
String s_date= request.getParameter("startdate");
pageContext.setAttribute("s_date", s_date);
String e_date= request.getParameter("enddate");
pageContext.setAttribute("e_date", e_date);
ref.refarray_vac1(s_date,e_date);
ref.ClosestToMultiplesOfTen_User(s_date,e_date);
%>
<%
//Comaprision reference = new Comaprision();
String ref_name= request.getParameter("ref_logtime");
pageContext.setAttribute("ref_name", ref_name);
ref.FindClosestToMultiplesOfTen(ref_name);
ref.refernece(ref_name);
%>
<br><br><br>
<table width = "170%" border = "1" cellspacing="0" cellpadding="0">
<tr>
<th>Date_Time</th>
<th>beam_current</th>
<th>beam_energy</th>
<%
for(int i=51; i<99;i++){
%>
<th>p<%=i%>_readback</th>
<th>p<%=i%>_setvalue</th>
<th>p<%=i%>_vmeset</th>
<th>p<%=i%>_dacbyadc</th>
<%
}
%>
<!--
</tr>
<c:set var="count" value="0" scope="session" />
<c:forEach var="row" items="${ref.refarray_vac1(param.startdate,param.enddate)}">
<c:forEach var="r" items="${ref.refernece(param.ref_logtime)}" begin="${count}" end="${count}">
<tr bgcolor="darkgray ">
<td><c:out value="${r.logtime}"></c:out></td>
<td>
<c:out value="${r.beam_current}"></c:out> </td>
<td>
<c:out value="${(r.beam_energy)}"/>
</td>
<td>
<fmt:formatNumber value="${(r.p51_readback)}" maxFractionDigits="2" minIntegerDigits="2" var="mm"></fmt:formatNumber>
<c:out value="${(r.p51_readback)}"/>
</td>
<td>
<fmt:formatNumber value="${(r.p51_setvalue)}" maxFractionDigits="2" minIntegerDigits="2" var="mm"></fmt:formatNumber>
<c:out value="${(mm)}"/>
</td>
</tr>
<!-- For user_selection color name-- darkkhaki -->
<tr bgcolor="cornsilk">
<td><c:out value="${row.logtime}"></c:out></td>
<td>
<c:out value="${row.beam_current}"></c:out> </td>
<td>
<c:out value="${(row.beam_energy)}"/>
</td>
<td>
<fmt:formatNumber value="${(row.p51_readback)}" maxFractionDigits="2" minIntegerDigits="2" var="mm"></fmt:formatNumber>
<c:out value="${(row.p51_readback)}"/>
</td>
<td>
<fmt:formatNumber value="${(row.p51_setvalue)}" maxFractionDigits="2" minIntegerDigits="2" var="mm"></fmt:formatNumber>
<c:out value="${(mm)}"/>
</td>
</tr>
<tr>
<td>Deviation</td>
<jsp:include page="Mps_Hs_diff.jsp"></jsp:include>**Here I need to include another jsp as the cod ewas becoming large**
<c:set var="count" value="${count + 1}" scope="session" />
</c:forEach>
</c:forEach>
</table>
</body>
The another page where I need the values of r and row which are declared in this page is
<body>
<jsp:useBean id="ref" class="comp_Mps.Comp_Mps_hs"/>
<br>
<%
//Comaprision obj = new Comaprision();
String s_date= request.getParameter("startdate");
pageContext.setAttribute("s_date", s_date);
String e_date= request.getParameter("enddate");
pageContext.setAttribute("e_date", e_date);
ref.refarray_vac1(s_date,e_date);
ref.ClosestToMultiplesOfTen_User(s_date,e_date);
%>
<%
//Comaprision reference = new Comaprision();
String ref_name= request.getParameter("ref_logtime");
pageContext.setAttribute("ref_name", ref_name);
ref.FindClosestToMultiplesOfTen(ref_name);
ref.refernece(ref_name);
%>
<br><br><br>
<table width = "170%" border = "1" cellspacing="0" cellpadding="0">
<c:set var="row" value="${ref.refarray_vac1(param.startdate,param.enddate)}"></c:set>
<c:set var="r" value="${ref.refernece(param.ref_logtime)}"></c:set>
<tr>
<td scope="row" style="${r.beam_current-row.beam_current eq 0 ? 'background-color: lime':'background-color: pink'}">
<fmt:formatNumber value="${(r.beam_current-row.beam_current)}" maxFractionDigits="2" minIntegerDigits="2" var="mm"></fmt:formatNumber>
<c:out value="${mm}" ></c:out></td>
<td scope="row" style="${r.beam_energy-row.beam_energy eq 0 ? 'background-color: lime':'background-color: pink'}">
<fmt:formatNumber value="${(r.beam_energy-row.beam_energy)}" maxFractionDigits="2" minIntegerDigits="2" var="mm"></fmt:formatNumber>
<c:out value="${mm}" ></c:out></td>
<td style="${r.p51_readback-row.p51_readback eq 0 ? 'background-color: lime':'background-color: pink'}">
<fmt:formatNumber value="${((r.p51_readback-row.p51_readback))}" maxFractionDigits="2" minIntegerDigits="2" pattern="##.##" var="nn"></fmt:formatNumber>
<c:out value="${nn}"></c:out>
<fmt:formatNumber value="${(r.p51_readback-row.p51_readback)/r.p51_readback}" maxFractionDigits="2" minIntegerDigits="2" type="percent" var="mm"></fmt:formatNumber>
<c:out value="(${mm})" ></c:out></td>
But the first page is never called by the user, an another page is called on whose button click the first jsp is called.So the values in the page which I included are never processed as it is never called.
One option is to use the session scope in order to have your variable available in any JSP or servlet during the current session.
You can store your variables in the session scope:
HttpSession session = request.getSession();
String variableToPass = "hello";
session.setAttribute("variableToPass", variableToPass);
And, you can access them like this:
HttpSession session = request.getSession();
String variablePassed = session.getAttribute("variableToPass");
Hope it is helpful.
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.