Java Jstl foreach - java

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!

Related

how to iterate through jstl list to match condition in java spring mvc

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.

Sending data using <a href="#"> in the same page and display the result (FORM) using JSP without changing the (FORM) coding

<div id="main_search">
<table>
<tr>
<td>Product</td>
<td>:</td>
<td>
<input type="checkbox" name="product" class="prod_checkbx" value="Bilateral-VC">Bilateral-VC
<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Bilateral Non-VC">Bilateral Non-VC
<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Budget Domestic">Budget Domestic
<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Budget High">Budget High
<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Budget International">Budget International
<br>
<input type="checkbox" name="product" class="prod_checkbx" value="IDD Buffet Base">IDD Buffet Base
<br>
<input type="checkbox" name="product" class="prod_checkbx" value="Premium">Premium
<br>
</td>
</tr>
<tr>
<td>Destination</td>
<td>:</td>
<td>
<input id="destination" type="text" name="destination" />
</td>
</tr>
<tr>
<td colspan="9" align="center">
<a id="search" name="search" class="button orange small" style="cursor:pointer" href="#">SEARCH</a>
</td>
</tr>
</table>
</div>
<div id="search_result" style="overflow: auto;">
<h2>Floor Price Edit</h2>
<table id="result-tbl" class="searchTable">
<tr>
<th>Destination</th>
<th>Product</th>
</tr>
<tr>
<% String dest=r equest.getParameter( "destination"); %>
<td>
<%=d est %>
</td>
</tr>
<% if (dest !=n ull) { %>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3307/icars" user="root" password="" />
<sql:query var="dest_result" dataSource="${dbsource}">
SELECT * from icx_pricing_desk WHERE DESTINATION LIKE '
<%=d est %>%'
</sql:query>
<c:forEach var="row" items="${dest_result.rows}">
<tr>
<td>
<c:out value="${row.DESTINATION}" />
</td>
</tr>
</c:forEach>
<% } %>
<td>
<% String products[]=r equest.getParameterValues( "product"); %>
<% if(products !=n ull) { %>
<% for(int i=0; i<products.length; i++) { %>
<%=products[i]%>
<sql:query var="prod_result" dataSource="${db }">SELECT * FROM icx_pricing_desk WHERE PRODUCT = '
<%=products[i]%>'</sql:query>
<c:forEach var="row" items="${prod_result.rows}">
<tr>
<td>
<c:out value="${row.PRODUCT}" />
</td>
</tr>
</c:forEach>
<% } } %>
</td>
</table>
</div>
This is some kind of form without <form> tag and for submit button it didn't use <input type="submit"> like normal form. It use <a href="#"> to submit the data.
The question is how do you send the data using the <a href="#">???
In addition, when i click the SEARCH button both <% String dest = request.getParameter("destination"); %> and <% String products[]= request.getParameterValues("product"); %> didn't received any data.
When using the standard form, both can display result. This code is written in same page(JSP).
--The first coding cannot be changed because it was the assignment and need to solve it.--
Add a form tag in your code like
<form name="form1" method="POST">
<table>
<!-- Your code ->
<a id="search" name="search" class="button orange small" style="cursor:pointer" href="javascript:void(0);" onclick="document.form1.submit();">SEARCH</a>
</table>
</form>
Things to remember
Form tag: method(POST), Name of form(form1)
Method called on onclick of a tag

Display results on the same JSP issue

I have a created a small Java web application. I have made use of DAO and a JSP file. My issue is that when I enter an isbn number in the input field, if the book is found in the database, it displays me "Book Found" and the corresponding details. But if I enter an isbn number in the input field, and if the book is not found in the db, it still displays me "Book Found" but with isbn number 0 and book title "null" which I don't want. In that case, it should display me only "Book not found".
Note that the problem lies mainly in the JSP page.
Here is my full code: http://pastebin.com/cTZy4w6V (using pastebin since the code is too long)
Here is the JSP code:
<jsp:useBean id = "bm" class="book.ManagerBook" scope = "session"/>
<h1> Welcome to ABC Library</h1>
<form>
<table>
<tr>
<td> Enter Details </td>
<td><input type="text" name="isbn"></td>
<td><input type="submit" name="find" value="find"></td>
</tr>
</table>
<input type="hidden" name="submitted" value="true">
</form>
<%
Boolean submitted = Boolean.parseBoolean(request.getParameter("submitted"));
if(submitted){
int isbn = Integer.parseInt(request.getParameter("isbn"));
Book b2 = bm.findBook(isbn);
%>
<table>
<tr>
<td colspan=2>
<h2>Book Found</h2>
</td>
</tr>
<tr>
<td><h3>ISBN</h3></td>
<td><h3>Title</h3></td>
</tr>
<tr>
<td><%= b2.getIsbn()%></td>
<td><%= b2.getTitle() %></td>
</tr>
</table>
<%}else if(!submitted){ %>
<h3> Book Not Found</h3>
<% } %>
If possible, don't use scriptlets in jsp. It's a bad practice.
Try something like this:
if(submitted){
int isbn = Integer.parseInt(request.getParameter("isbn"));
Book b2 = bm.findBook(isbn);
if (b2.getTitle() != null) {
%>
<table>
<tr>
<td colspan=2>
<h2>Book Found</h2>
</td>
</tr>
<tr>
<td><h3>ISBN</h3></td>
<td><h3>Title</h3></td>
</tr>
<tr>
<td><%= b2.getIsbn()%></td>
<td><%= b2.getTitle() %></td>
</tr>
</table>
<% } else { %>
<h3> Book Not Found</h3>
<% } %> }

How to pass variables defined in one jsp to another and then again after processing in another jsp include that jsp in first jap page

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.

How to validate <aui:select> in a Liferay Form?

In View.jsp I created a form by using . there are some inputs and 3 select-box on it, actually I want to validate all of them. for inputs I used but I don't know how can I validate my
Actually I want to validate these three :
<aui:select id="birthday_day" name="birthday_day">
<aui:select id="birthday_month" name="birthday_month">
<aui:select id="birthday_year" name="birthday_year">
This is my view.jsp
<portlet:actionURL var="myUrl">
</portlet:actionURL>
<aui:form enctype="multipart/form-data" action="<%= myUrl %>" method="POST" name="fm">
<table border="0" bgcolor=#ccFDDEE>
<tr>
<td colspan="2" align="center"><b>Recruiment Form</b></td>
</tr>
<tr>
<td colspan="2" align="center"></td>
</tr>
<tr>
<td><b>First Name:<span>*</span></b></td>
<td>
<aui:input name="fname" type="text">
<aui:validator name="required"/>
</aui:input>
</td>
</tr>
<tr>
<td><b>Last Name:<span>*</span></b></td>
<td>
<aui:input name="lname" type="text">
<aui:validator name="required"/>
</aui:input>
</td>
</tr>
<tr>
<td><b>Father Name:<span>*</span></b></td>
<td>
<aui:input name="father_name" type="text">
<aui:validator name="required"/>
</aui:input>
</td>
</tr>
<tr>
<td><b>Birth Date:<span>*</span></b></td>
<td>
<aui:select id="birthday_day" name="<portlet:namespace/>birthday_day">
<aui:option value="0">روز</aui:option>
<%
for(int i=1;i<=31;i++) {
%>
<aui:option value="<%=i%>"><%=i%></aui:option>
<%
}
%>
</aui:select>
/
<aui:select id="birthday_month" name="birthday_month">
<aui:option value="0">ماه</aui:option>
<%
String[] monthBirthDay = {"فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"};
for(int j=0;j<monthBirthDay.length;j++) {
%>
<aui:option value="<%=j+1%>"><%=monthBirthDay[j]%></aui:option>
<%
}
%>
</aui:select>
/
<aui:select id="birthday_year" name="birthday_year">
<aui:option value="0">سال</aui:option>
<%
String[] yearBirthDay = {"1370","1369","1368","1367","1366","1365","1364"};
for(int j=0;j<yearBirthDay.length;j++) {
%>
<aui:option value="<%=yearBirthDay[j]%>"><%=yearBirthDay[j]%></aui:option>
<%
}
%>
</aui:select>
</td>
</tr>
</table>
</aui:form>
How can I solve this issue??????
Please guide me.
<aui:select showEmptyOption="true" name="select hospital name" required="true">
</aui:select>
THis may help you.
just assign an id to the aui:select tag
<aui:select inlineField="true" label="xxx" name="xxx" id="xxxId">
and then you can get the value with this (javascript + AUI)
var selectedVal = A.one('#<portlet:namespace/>xxxId').val();
with the selected value you can perform any kind of validation.

Categories

Resources