I am new to JSP and servlet.
I am trying to have list from servlet and wants to display those data into JSP page.
Here is what I did
My Servlet class
List<User> list = friendsDao.getFirendsList(user.getEmail());
System.out.println("List Size:"+list.size());
req.setAttribute("list", list);
getServletContext().getRequestDispatcher("/home.jsp").forward(req, resp);
My JSP Page
I have added this tag library
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
and here is what I am doing to iterate the data
<table>
<c:forEach var="friend" items="${list}">
<tr>
<td><c:out value="${friend}" /></td>
<td><c:out value="${friend.email}" /></td>
</tr>
</c:forEach>
</table>
but this is not working
but when I am trying to have something like this
<%
}
List<User> list = (List<User>) request.getAttribute("list");
%>
<table>
<c:forEach var="friend" items="<%=list%>">
<tr>
<td><c:out value="${friend.name}" /></td>
<td><c:out value="${friend.email}" /></td>
</tr>
</c:forEach>
</table>
This is also not working but, it at list iterate the loop to the size of data. but in browser it prints
${friend.name} ${friend.eamil}
How can I have actual values in there.
Please help me with this.
Thanks,
Nixit
change
<c:forEach var="friend" items="<%=list%>">
to
<c:forEach var="friend" items="${list}">
because by <%=list%> it is outputting the value right there, and you don't need reference to List<User> in jsp
Ohk I got the solution,
I don't know the reason, but jsp file requires me to put this one line of code. in order to tag library to work
<%# page isELIgnored="false" %>
Related
I am working on a project to try and teach myself spring and struts. I am currently stuck on a JSP page. I have a pojo class with variables eid and ename with getters/setters, I also have a table in sql with the same values with six populated rows.I am accessing my database through a JdbcTemplate and have stored the result in a list, I then passed this list to my action page in which I set it as a request.setAttribute("empList",eList). In my jsp page I call that attribute and then try to iterate through it using JSTL. However nothing shows up, I know that my list variable has data in it since i checked it using the expression tag <%=eList%> and objects show up like this:
[org.classes.database.Employee#d9b02,
org.classes.database.Employee#13bce7e,
org.classes.database.Employee#171cc79,
org.classes.database.Employee#272a02,
org.classes.database.Employee#137105d,
org.classes.database.Employee#1359ad]
I thought that maybe I was missing something on jstl but I have jstl-1.2 in my META-INF/lib folder. I have also tried to add it in the configure path file and still nothing. I also have the correct tag url. Also when I do a simple <c:out value="Hello"/>. Hello does print out. So this leads me to believe that my jstl is working properly, but when I try iterating through my list using jstl nothing shows up at all.Anyways here is my JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO- 8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page import="java.util.List"%>
<!DOCTYPE html>
<% List eList = (List)session.getAttribute("empList");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Details</title>
</head>
<body>
<c:out value="Hello"></c:out>
<h3>Employee Details</h3>
<hr size="4" color="gray"/>
<table>
<%=eList%>
<c:forEach items="${eList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Any help would be highly appreciated!
Before teaching yourself Spring and Struts, you should probably dive a little deeper into the Java language. Output like this
org.classes.database.Employee#d9b02
is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java.
The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class.
Your JSTL here
<c:forEach items="${eList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList.
You need to add it
<% List eList = (List)session.getAttribute("empList");
request.setAttribute("eList", eList);
%>
Or use the attribute empList in the forEach.
<c:forEach items="${empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
change the code to the following
<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
<%
for(int i=0; i<eList.length;i++){%>
<tr>
<td><%= ((Employee)eList[i]).getEid() %></td>
<td><%= ((Employee)eList[i]).getEname() %></td>
</tr>
<%}%>
</table>
you can read empList directly in forEach tag.Try this
<table>
<c:forEach items="${sessionScope.empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.eid}"/></td>
<td>Employee Pass: <c:out value="${employee.ename}"/></td>
</tr>
</c:forEach>
</table>
<c:forEach items="${sessionScope.empL}" var="emp">
<tr>
<td>Employee ID: <c:out value="${emp.eid}"/></td>
<td>Employee Pass: <c:out value="${emp.ename}"/></td>
</tr>
</c:forEach>
another example with just scriplets, when iterating through an ArrayList that contains Maps.
<%
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");
for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>
</tr>
...
<%}%>
enter image description hereI have a table of users data which have been retrived below using JdbcTemplate of Spring:
List<UserDetailsBean> userdetails = UserDetailsDaoObj.getallUserDataDetails(u.getId());
these details needs to be displyed in the jsp so im setting the object userdetails as below:
modelAndView.addObject("userdetails",userdetails);
I'm not able to retrieve the details in JSP the code used in JSP is below:
<c:forEach var="user" items="${userdetails}"><tr><td>${user.getId()}</td><td>${user.getAddress()}</td><td>${user.getCity()}</td><td>${user.getCountry()}/td></tr></c:forEach>
You just need to access properties of UserDetails like this
<c:out value="${user.id}" />
<c:out value="${user.address}" />
assuming that you have standard accessors method present in your class
You need to do something like this in JSP:
<c:forEach items="${userdetails}" var="user">
<tr>
<td>User ID: <c:out value="${user.id}"/></td>
<td>User address: <c:out value="${user.address}"/></td>
</tr>
</c:forEach>
You need to use JSTL tags to fetch values, In your case it is <c:out>.
Also try accessing elements using field name and not getters()
<c:forEach var="user" items="${userdetails}">
<tr>
<td><c:out value="${user.id}"/></td>
<td><c:out value="${user.country}"/></td>
</tr>
</c:forEach>
Well from what you posted its not really clear what your issue might be , but an obvious error , is what the others posted in their answers.
Note that * in order to operate properly , you have to place this line on top of your JSP.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Also the same for the jstl library. It must exist in your classpath.
link
I was wondering if I could pass parameters through URL to a specific action.
what I would like to do, is something like this (written using jstl core):
<c:forEach items="${listaApprodi}" var="app">
<tr>
<td></c:out></td>
</tr>
</c:forEach>
Of course I won't use a servlet as "destination" but I'll use an action named OrariAction.class.
Is it possible with Struts2 taglib?
One of the possible solution is
<%# taglib uri="/struts-tags" prefix="s" %>
<c:forEach items="${listaApprodi}" var="app">
<tr>
<td>
<s:url action="your-ActionName" var="myurlvar" >
<s:param name="app">${app.name}</s:param>
<s:param name="lin">${requestScope.linea.name}</s:param>
</s:url>
<s:a href="%{myurlvar}">${app.name}</s:a>
</td>
</tr>
</c:forEach>
You can also use <s:iterator> instead of <c:foreach>
I am working on servlet and jsp project. I am passing an object from servlet to JSP. And currently I am iterating that object and showing them in a table -
Below is my code in jsp -
<TABLE id="tableSMS" BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
<TR style="color:#ffffff;background-color:#787878;">
<TH>Hash Name</TH>
<TH>Database Name</TH>
<TH>Version</TH>
</TR>
<c:forEach var="i" begin="0" end="${reportCount.getHash().size() - 1}">
<TR>
<TD>
${reportCount.getHash().get(i)}
</TD>
<TD>
${reportCount.getDatabaseName().get(i)}
</TD>
<TD>
${reportCount.getVersion().get(i)}
</TD>
</TR>
</c:forEach>
And above code is working fine and I am able to show the data properly. Now what I need to do is -
${reportCount.getDatabaseName().get(i)} will return database name as oracle or mysql only. Now I need to calculate what is the percentage of oracle database. I will get the total number of records from ${reportCount.getHash().size(). So if total number of records is 10 and oracle database is present 5 times, then the percentage should be 50%.
Now I am not sure how would I calculate the above percentage using that object? And after calculating that percentage, I need to show the result in a new table which is shown below -
<table>
<tr>
<th style="background-color: #E8E8E6;"><b>Oracle Database</b></th>
</tr>
<tr>
<!-- I would like to show the percentage in this row -->
<td>%</td>
</tr>
</table>
I am thinking I should iterate the reportCount object again in the above new table and extract the percentage here but not sure how would I do that? Can anyone provide an example?
UPDATE:-
Here is my bean code -
public class Response {
private List<String> hash = new LinkedList<String>();
private List<String> databaseName = new LinkedList<String>();
private List<String> version = new LinkedList<String>();
// getters and setters here
}
There are three things as following:
Add the functions taglib:
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Add reportsCounts variable to requestScope instead of session if not required on any other page & use as following:
<c:set var="oracleDBCount" value="0" scope="page" />
<c:forEach var="reportCount"
items="${requestScope.reportCounts.databaseName}" varStatus="loop">
<TR>
<TD>${requestScope.reportCounts.hash[loop.index]}</TD>
<TD>${reportCount}
<c:if test="${reportCount == 'ORACLE'}">
<c:set var="oracleDBCount" value="${oracleDBCount + 1}" scope="page"/>
</c:if>
</TD>
<TD>${requestScope.reportCounts.version[loop.index]}</TD>
</TR>
</c:forEach>
Now display percentage as:
${(oracleDBCount / fn:length(requestScope.reportCounts))*100}%
Based on my experience, doing number-crunching on a JSP page can make it unreadable very quickly. Also you may encounter additional requirements in the future such as:
Text matching (Are you guaranteed that the value is always "oracle"? Or can it become "ORACLE" or "Oracle"?
What if there are zero reports? Then you will need an if-condition to prevent division by zero.
If your client says "We have more report servers like MS, Postgres...can you show the percentage of those?"
Is it possible to do the computation inside the servlet while you are making the reportCount object?
Then you can pass the value inside a session attribute
request.getSession(true).setAttribute("oracleReports", "50%")
and then in the JSP output something like
<c:out value="${sessionScope.oracleReports}"/>
Use JavaScript for doing the operation, Here is the code
Read the comments to understand the code.
Add an id to the so that i can read the inner content using
javascript. Appended id with the index so that each raw gets different
id's
<c:forEach var="i" begin="0" end="${reportCount.getHash().size() - 1}">
<TD id="databaseName<c:out value='${i}' />">
${reportCount.getDatabaseName().get(i)}
</TD>
Add Id to the so that i can set values to the raw using
JavaScript
<tr>
<td id="oraclePercentage">%</td>
<td id="mySQLPercentage">%</td>
</tr>
call the javascript function to set the values to the raw, as we don't
have any button to trigger we open a raw and add the JavaScript call
from the JSP so that the script is triggered every time the page loads
the raw.
<TR><TD><Script>setPercentage('${reportCount.getHash().size() - 1}');</script><TD><TR>
what to do is defined here
<Script>
function setPercentage(var index){
for(var i=0; i<index;i++){
var documentType=document.getElementById("databaseName"+i).innerHTML;
var oracleCount=0;
var mySQLCount=0;
if(vardocumentType=='Oracle')
oracleCount+=(Number)1;
else if(vardocumentType=='MySQL')
mySQLCount+=(Number)1;
document.getElementById("oraclePercentage").innerHTML=(oracleCount/index)*100;
document.getElementById("mySQLPercentage").innerHTML=(mySQLCount/index)*100;
}
</script>
I want to create an arraylist of objects in JSP.
And after that, want to loop through the list objects.
can some one please help me in creating it.
Create the ArrayList at servlet set it as attribute, and iterate it on JSP using <c:forEach>
Servlet
List<Foo> list = new ArrayList<Foo>();
list.add(foo1);
list.add(foo2);
list.add(foo3);
request.setAttaribute("fooList", list);
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
hello.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${list}" var="foo">
<tr>
<td><c:out value="${foo.name}" /></td>
<td><c:out value="${foo.age}" /></td>
</tr>
</c:forEach>
Note: name and age are two properties of Foo with proper accessor methods