how to remove the duplicated element in the table JSP JAVA array - java

I have two arrays:
<%String TXTfileArray[] = (String[])request.getAttribute("txt");%>
<%String TXTContentArray[] = (String[])request.getAttribute("content");%>
the data in the array is repeated.
by using the following statement in JSP i can output the array in the table:
<table border="1">
<tr>
<th>txt name</th>
<th>txt content</th>
</tr>
<% for (int i=0; i< TXTfileArray.length;i++){ %>
<tr>
<td> <%=TXTfileArray[i] %> </td>
<td> <%=TXTContentArray[i] %> </td> <%} %>
</tr>
</table>
how to remove the repeated element in the table?
Please do not hard code, as the array is not fixed. the array is depended on the other process.

You could try adding each element in a Set, and if it already exists don't add it to the table:
<% Set<String> a = new HashSet<>();
for (int i=0; i< TXTfileArray.length;i++)
if (a.add(TXTfileArray[i]) { %>
<tr>
<td> <%=TXTfileArray[i] %> </td>
<td> <%=TXTContentArray[i] %> </td> <%} %>
Although I think JB Nizet's suggestion of using LinkedHashSet<SomeClass> is probably a better way to do it.

Related

Loop inside loop - Display ArrayList

I'm trying to diaplay ArrayList in JSP. I have to ArrayLists I want to loop through and display the data in the same JSP table. This works fine, for the first Arralist (history), but when I get to the second it displays all the ArrayList in each row, instead of the current index from the loop:
<table id="test" class="table text">
<tr>
<th>Result</th>
<th>Deposit</th>
<th>Bet</th>
<th>Return +/-</th>
<th>Current balance</th>
<th>Date</th>
</tr>
<%
for (history his : history) {
%>
<tr class="listing">
<td><%=his.getRes()%></td>
<td><%=resultTwoDecimalsDeposit%></td>
<td><%=his.getOdds()%></td>
<td><%=his.getDate() %> </td>
<td style="color:#00cc00;"> + <%=resultTwoDecimalsRet%> </td>
Everything is fine until here. Instead of showing the current index from the loop, it displays all the ArrayList in each tr
<% for (int i = 0; i < list1.size(); i++) {
%>
<td><%=list1.get(i) %></td>
<% } %>
<%}}}%>
</tr>
</table>
Your problem is because of the nested loop. For each his, the complete inner for loop is executing which you do not want. You want that for each history element, the corresponding value from list1 is displayed.
Do it as follows:
<table id="test" class="table text">
<tr>
<th>Result</th>
<th>Deposit</th>
<th>Bet</th>
<th>Return +/-</th>
<th>Current balance</th>
<th>Date</th>
</tr>
<%for (int i=0; i<history.size() && i<list1.size(); i++) {%>
<tr class="listing">
<td><%=history.get(i).getRes()%></td>
<td><%=resultTwoDecimalsDeposit%></td>
<td><%=history.get(i).getOdds()%></td>
<td><%=history.get(i).getDate() %> </td>
<td style="color:#00cc00;"> + <%=resultTwoDecimalsRet%> </td>
<td><%=list1.get(i) %></td>
</tr>
<%}%>
</table>

I want to give 'edit-link i.e <a>edit</a>' if ans column of table from database is null

I am retrieving answer from ans column by using jdbc and showing it into a jsp page in a form of a table, if ans column is null or empty then I have to give a user edit link, but if ans column has a value then I'm going to show answer but the problem is if-else condition is not working. Please help me to solve this, My code is given below:
<div class="table-responsive">
<table class="table center-aligned-table">
<thead>
<tr class="text-primary">
<th>Question No</th>
<th>Question Name</th>
<th>Answer:</th>
<th> </th>
<th> </th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<%
try{
int oopa=1;
//String nme=(String)session.getAttribute("vname7");
DbCon cc=new DbCon();
Connection onn=cc.fun();
Statement stt=onn.createStatement();
ResultSet r=stt.executeQuery("select ques,ans from postquestion;");
while(r.next()){
%>
<tr class="">
<td><center><%=oopa++%></center></td>
<td><%=r.getString(1)%></td>
<%
if(r.getString(2)==null)
{
%>
<td>Edit</td>
<%
}
else
{
%>
<td><%=r.getString(2)%></td>
<%
}
%>
<td> </td>
</tr>
<%
}
}
catch(Exception vjin){
System.out.println("I am vjin: "+vjin);
vjin.printStackTrace();
}
%>
</tbody>
</table>
</div>
You might get empty values from your results. So check if r.getString(2) is empty or not, null differs from empty value.
More over, JSP is just a view component, writing DAO code in JSP is not a good practice.
Thanks
You can check for null values using wasNull() method of ResultSet.For example like below :
<%
//getting value of column in "a"
String a = r.getString(2);
//checking if resultset return null i.e a is null then do below:
if(r.wasNull())
{
%>
<td>Edit</td>
<%
}
else
{
%>
<td><%=r.getString(2)%></td>
<%
}
%>

Java Jstl foreach

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!

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 print one row value at a time, How to Iterate List in JSTL

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>

Categories

Resources