While Loop issue when querying Database in JSP - html

I am having trouble understanding why my codes does not work as I had thought. I am having issue in having my input text value to be that of my resultset value. Let me apologise for my bad explanation. Before I continue, I would like to mention that I am using JSP to run my application.
Say in my database, I have the following names, "Peter", "John" , "Simon" and when I queried, I will store their names in a hidden input text, as the names will be used for other usage. But I am facing the issue where by only "PETER" name is registered in the input text, as Peter is the first entry in the database.
Below is an abstrace of my while loop. If anyone know whats the underlying cause please let me know. Thanks in advance guys.
<%while (rs.next()) { %>
<tr><td>
<img alt="logo" src= "<%= rs.getString("ItemImage")%>" width="600" height = "400"/><button type="button" onclick="initialize2()" width="600" >Location</button>
</td>
<td>
<input type = 'hidden' id = 'itemName' value = "<%=rs.getString("ItemName")%>" />
<input type = "hidden" id = "address" value = "<%= rs.getString("ItemLocation")%>" />
<div id="<%= rs.getString("ItemName")%>" style="width: 600px; height: 400px;"></div>
</td>
</tr>
<% } %>

You are repeating the same id over and over which registers only one input text.
Try, for example:
<% string name = "itemName" + counter; %>
<input type='hidden' name="<%=name%>" value="<%=rs.getString("ItemName")%>" />

Related

if statement not executed in JSP scriptlet

i encountered the following problem. I have made a table in mysql named 'users' and i want to add users using JSP. The primary key is the Email and i want to check before adding another user if the email already exists. If the email already exists the users will not be added to the database and a message "email already exists" will appear.
I created ResultSet rs object and extracted the "Email" column into a String email using a while loop.Now, here comes the problem. Suppose i have a user with the "denis#yahoo.com" email. If i try to add an user with the exact same email an error will occur which means my if statement was ignored. I looked up in the debug mode for the variables email and Email and they had the exact same "denis#yahoo.com" and still the if statement was ignored.
<!-- file name: addUser.jsp -->
<%
String Email=request.getParameter("Email");
String Name = request.getParameter("Name");
String Adress = request.getParameter("Adress");
String Phone = request.getParameter("Phone");
if (Email != null)
{
jb.connect(); // connect to the database using JavaBean class
ResultSet rs;
rs=jb.seeTable("users");// rs gets first row of table
String email;
int a=1;
while(rs.next())
{
email=rs.getString("Email");
if(Email==email)
{
a=0;
jb.disconnect();
%>
<p> The email already exists</p>
<%
break;
}
}
if(a==1){
jb.addUser(Email,Name, Adress, Phone);
jb.disconnect();
%>
<p>Data has been added.</p>
<%
}
} else {
%>
<form action="addUser.jsp" >
Email: <input type="text" name="Email"><br>
Name: <input type="text" name="Name"><br>
Adress: <input type="text" name="Adress"><br>
Phone: <input type="text" name="Phone"><br>
<button type="submit" >Add User</button><br>
</form>
<%
}
%>
I use NetBeans IDE 8.2, and something that i think is odd appeared in the debug mode. One of the email i try to test appeared with bold characters meanwhile the other was not bold.
Why is my if statement ignored if i add an user with the exact same email of another? Please help me out!

ejs string variable with space is not displayed properly

I am trying to display the search query in the search bar in HTML.
But if the variable includes a space, the webpage is only going to display the first word.
Here is the code
app.get('/search', function(req, res) {
console.log(req.originalUrl,'oro')
console.log(req.query['search_query'],'aaaaaaa')
res.render('search.ejs', {
user : req.user,
query : req.query['search_query']
});
});
Here is the html code
<form action="/search" method="get">
<div class="form-group">
<input type="submit" class="btn btn-warning btn-lg" value = "search" style = "float: right"/>
<div style="overflow: hidden; padding-right: .5em;">
<input type="text" value = <%= query %> class="form-control" name="search_query" style = "width:100%;"/>
</div>
</div>
</form>
query is the variable collected from the last webpage and passed to /search.
If I type in "I want to find xx", the webpage will only display "I" in the search box. However, in the console, the printout result is the full query " I want to find xx". The corresponding url is also correct "/search?search_query=I+want+to+find+xx".
Anyone has an idea? Thanks a lot!
Let's start with correcting your HTML, by using quotes in value:
<input type="text" value = "<%= query %>" class="form-control" name="search_query" style = "width:100%;"/>
Here under IE you should see a large error, on FF and Chrome browser will try to save the situation and catch only the first word.
Prolably rest of your words are used as attributes and ignored in this input.
Change <%= query %> to <%- query %> .
To add a new line or space while working with ejs, you will have to replace string parameters with HTML tags.
For example, here, I am replacing \n => < br/> to add a new line
<% var testVar = 'Line1\nLine2' %> <%- testVar.replace(/\n/g, '<br/>') %>
Change <%= query %> to <%- query.replace(/ /g, " ") %>
I struggled for hours to render text with spaces
Adding quotes seems to be the easiest solution to this
value = "<%= query %>"
to solve partial content change:
<%= to <%-
use: `` with "" inside
JS example:
let txt = "some text"
console.log(`"${txt}"`)

If statement in HTML

Hello i have list of products this my html
<telerik:RadListBox ID="RadListBox1" runat="server" DataSourceID="LinqDataSourceCategories" Height="200px" Width="250px" CssClass="ui-droppable" >
<EmptyMessageTemplate>
No records to display.
</EmptyMessageTemplate>
<ItemTemplate >
<div class="ui-draggable ui-state-default" data-shortid="<%#Eval("ID")%>">
<em>Active : </em><span><%# Eval("LoadProduct") %></span><br />
<em>ProductId: </em><span><%# Eval("ProductId") %></span><br />
</div>
</ItemTemplate>
</telerik:RadListBox>
I have Active that is say if LoadProduct true or false
in client it look like this
<em>Acrive : </em>
<span>False</span>
<br>
<em>ProductId: </em>
<span>101-01-056-02</span>
<br>
<em>ShortID: </em>
<span class="ShortID" data-shortid="0">0</span>
<br>
I want to replace text with img ,i need to check if <%# Eval("LoadProduct") %> ==true put img scr=/green.png/ else img scr=/red.png/ that clien will look like this
<em>Acrive : </em>
<span><img src='green.jpg'/></span>
<br>
<em>ProductId: </em>
<span>101-01-056-02</span>
<br>
<em>ShortID: </em>
<span class="ShortID" data-shortid="0">0</span>
<br>
Sow how it can be done?
To add if statement to HTML,
or to catch event that building all elements and there check if LoadProduct==true and append html to item?
try this
<em>Active : </em><span><%# Convert.ToBoolean(Eval("LoadProduct")) ? "<img src='green.jpg'/>" : "<img src='red.jpg'/>"%></span><br />
Come to think of it, I don't really like the idea of back-end conditionals in front-end.
Code-behind is one thing and frontside is the other - it's not a good idea to mix it if it isn't inevitable.
The purest way to get that would be to set the variable (or a function, in your case) in code-behind and just to show it in front-end, like:
Code behind:
protected string GreenOrRed(bool isLoadProduct)
{
return isLoadProduct ? "green" : "red";
}
(the function or variable has to be at least protected in order to be accessible in aspx page, because the aspx page is the derivative from base class of aspx.cs )
front-end:
<span><img src='<%# GreenOrRed((bool)Eval("LoadProduct")) %>.jpg'/></span>
After that, remeber to add
this.DataBind();
in your Page_Load() function.
Let the code-behind decide, let the front-end only show the result.
<%
if((bool)Eval("LoadProduct") == true)
{
Response.Write("src='green.jpg'");
}
else Response.Write("src='red.jpg'");
%>
Try this
<img src='<%# (bool)Eval("LoadProduct") ? "green.jpg" : "red.jpg" %>'/>

Display data from Custom Query(Joined tables) in liferay search container

I have followed this wiki and have successfully built a custom query.
It works fine. I have used a join between tables.
My question is how do I display it on a jsp using liferay search container since className in search container requires one model class.
EDIT:
What I have tried till now is this:
<%
getAttendanceData attName = new getAttendanceData();
List<Object[]> displayAttListName = AttendanceLocalServiceUtil.findAttendance();
ArrayList name = new ArrayList();
ArrayList title = new ArrayList();
ArrayList status = new ArrayList();
ArrayList remarks = new ArrayList();
for(Object[] att:displayAttListName) {
name.add(att[0]);
title.add(att[1]);
status.add(att[2]);
remarks.add(att[3]);
}
%>
<liferay-ui:search-container delta="20" emptyResultsMessage="No Results Found">
<liferay-ui:search-container-results
total="<%= displayAttListName.size() %>"
results="<%= ListUtil.subList(displayAttListName , searchContainer.getStart(), searchContainer.getEnd()) %>"
/>
<liferay-ui:search-container-row modelVar="search"
className="java.lang.Object">
<%
for(Object displayName:name) {
%>
<liferay-ui:search-container-column-text name='studName' value = '<%=String.valueOf(displayName)%>' href="">
</liferay-ui:search-container-column-text>
<%
}
%>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator/>
</liferay-ui:search-container>
What I have done above displays each of the 10 names 10 times in a column.
I want the names to appear on each new row. How shoould I modify the above code?
EDIT 2
Considering the name array defines earlier I did the following:
<liferay-ui:search-container-column-text name="employee name" href = "">
<%=name.getClass().getDeclaredFields().toString() %>
</liferay-ui:search-container-column-text>
With the above, I am getting the result something like: [Ljava.lang.reflect.Field;#195f1af on each row.
I see that the name, title, status and remarks field are all String (as per your comment) so in the for loop you should cast the Object as a String and you don't need the four ArrayList for this.
Here is how the row tag would look like:
<liferay-ui:search-container-row className="java.lang.Object" modelVar="search">
<%--
Since an "Object[]" is nothing but an "Object", we first cast the "search"
instance to an "Object[]" and then to a "String"
--%>
<liferay-ui:search-container-column-text name='name' value='<%= (String) ((Object[])search)[0] %>' />
<liferay-ui:search-container-column-text name='title' value='<%= (String) ((Object[])search)[1] %>' />
<liferay-ui:search-container-column-text name='status' value='<%= (String) ((Object[])search)[2] %>' />
<liferay-ui:search-container-column-text name='remarks' value='<%= (String) ((Object[])search)[3] %>' />
</liferay-ui:search-container-row>
There you go, this should work.
A more cleaner way I think would be to have a POJO defined that would store these values and then the POJO's list can be returned. I have not tried the second approach though.
Another standard approach is to include extra fields in any one of the entity's *Impl and then returning the list of that entity, in your case I would assume you have Student and Attendance entities, so you can put the fields status & remarks in StudentImpl and then return a List<Student> or put fname in AttendanceImpl and return List<Attendance> from the finder method. (updated after this comment)

How to display the contents of an arraylist in a drop down box

I have a sql statement that pulls infomration about tagnum's for individual pidm's. Every pidm can have multiple tagnum's so I am dropping the information into an arraylist. I want to display the contents of this arraylist in a dropdown box on a html page.
Here is the code for the arraylist:
<table style="border:transparent" style="width:100%">
<tr>
<td style ="width: 300px;">
<select style="width:150px;"tabindex="5" name="Tag">
<option></option>
<%} rscheck.close();
ResultSet rsTagCheck = stmt.executeQuery("SELECT PARKING.XKRPRMT.XKRPRMT_PIDM, PARKING.XKRPRMT.XKRPRMT_STATUS, PARKING.XKRPRMT.XKRPRMT_EXPIRE_YR, PARKING.XKRPRMT.XKRPRMT_TAG FROM PARKING.XKRPRMT WHERE XKRPRMT_PIDM ='" + BannerID + "'");
while (rsTagCheck.next()){
ArrayList<String> myTag = new ArrayList<String>();
myTag.add(rsTagCheck.getString("XKRPRMT_TAG"));
%>
<option><%= myTag.get(0) %></option>
</select>
</td>
I can get the first element to show in the drop down box, but anything after that show an outofbounds exception. I want to know how to display ALL of the information in the arraylist.
#Pointy I did that and all I got was this:
It put the first one in there, but the rest would not populate!!
There's no reason to create the array list at all.
while (rsTagCheck.next()) {
%>
<option><%= rsTagCheck.getString("XKRPRMT_TAG") %></option>
<%
}
edit — of course in practice you should be careful about what those strings might contain. If the strings come from some sort of user input, you shouldn't be just dumping them unwashed into the HTML. That's a whole other subject however.
Don't use scriptlets, use jstl tags and in this case
<c:forEach var="myTag" items="${rsTagCheck}">
and
<c:out value="${myTag.getString('XKRPRMT_TAG')}" />
Actually looking again at your code, I would not put the db query in a scriptlet! DB access should not be done here, pass the resultsets to jsp from servlet, and loop through data using jstl.