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>
...
<%}%>
Related
I was going through spring MVC tutorials and came across ModelAndView.
My JSP view looks like this,
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC </title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${student.getName()}</td>
</tr>
<tr>
<td>Age</td>
<td>${student.getAge()}</td>
</tr>
<tr>
<td>ID</td>
<td>${student.getBranch()}</td>
</tr>
</table>
</body>
</html>
It worked when I set both attribute name and attribute value in controller like the following,
ModelAndView mv = new ModelAndView();
mv.setViewName("result");
Student student = new Student("arun2", "CSE", 22);
mv.addObject("student",student);
return mv;
Then I came across other overloaded method ModelAndView.addObject(Object attributeValue) and I tried setting only attribute value mv.addObject(student); But this time it doesn't show student details in the browser.
My questions:
Is it possible to access those values in JSP by just setting attribute value as i did second-time mv.addObject(student);.
If yes, How? If not, Why do we have such overloaded method? Why do we need to set only value if we can't access it in the view (JSP)?
I went through the javadocs, But didn't find anything that could make me understand.
Yes, you can do it like that and access the parameters,but need to pay some attention.
Check the API for addObject at ModelAndView,it will shows method as below:
Then,let's look at the definition of ModelMap.addAttribute(Object)
It shows using a generated name,the definition of generated name listed as below:
So,if you just want to use the mv.addObject(student) method,you can access data in your jsp page as below:
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC </title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${student.name}</td>
</tr>
<tr>
<td>Age</td>
<td>${student.age}</td>
</tr>
<tr>
<td>ID</td>
<td>${student.branch}</td>
</tr>
</table>
</body>
</html>
If the object is a Group class, then you can get value via ${group.name}
And pay attention that the ModelAndView is from org.springframework.web.servlet.ModelAndView
Also,I suggest you use the EL Expressions to access data in your jsp page directly.
I want to display data from database in the browser with Spring MVC. Everything is alright, except my Thymeleaf template for each loop. Something is wrong there.
How can I display id data in ID row and name data in Name row iterating through the collection of objects with for each loop?
Source code:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table border="1">
<tr style="font-size: 13">
<td>ID</td>
<td>Name</td>
</tr>
<tr th:each="count : ${id}">
<td><p th:text="${count}" /></td>
<td><p th:text="${name}" /></td>
</tr>
</table>
</body>
</html>
Your question is not very clear, as you didn't specify your count object, and didn't show your controller.
Well supposing you have some entity Count with fields id and name, which you persist in the corresponding table of your database, and which you want to display in the Thymeleaf template.
To retrieve data from the database you need some Service or Repository class, that should have method that returns a List of your entities, example of such service method listAll():
public List<Count> listAll() {
List<Count> counts = new ArrayList<>();
countRepository.findAll().forEach(counts::add);
return counts;
}
Then you you need to set up the request mapping in your controller and add in that method an attribute to the model object, that will be a result of execution listAll() method. It may be done like:
#RequestMapping("/list")
public String countsList(Model model) {
model.addAttribute("counts", countService.listAll());
return "list";
}
Finally answering your question, your list.html template should contain the block:
<div th:if="${not #lists.isEmpty(counts)}">
<h2>Counts List</h2>
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="count : ${counts}">
<td th:text="${count.id}"></td>
<td th:text="${count.name}"></td>
</tr>
</table>
</div>
Read more info in Thymeleaf Documentation - Iteration Basics section.
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" %>
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 have read many posts that scriptlets is a bad practice so finally i decided to avoid this too. I have developed a project using struts framework in which mostly jsp pages have java code. And now i wanted to remove that code from my all the pages.
<%#page import="java.sql.ResultSet"%>
<%#page import="com.pra.sql.SQLC"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<table align="left" width="346" border="0">
<tr><td align="center" colspan="3" style="font-size:20px;">Tests We Provide</td></tr>
<tr>
<th width="80" height="38" nowrap>Test ID</th>
<th width="200" nowrap>Test Name</th>
<th width="144" nowrap>Test Fee</th>
</tr>
<%
String sql = "Select TestID,tname,tfee from addtest order by tname";
ResultSet rs = SQLC.getData(sql, null);
while (rs.next()) {
String testid = rs.getString("TestID");
String testname = rs.getString("tname");
String testfee = rs.getString("tfee");
%>
<tr>
<td width="80" height="34" nowrap><%=testid%></td>
<td width="200" nowrap><%=testname%></td>
<td width="144" nowrap><%=testfee%></td>
</tr>
<%
}
%>
</table>
Associate the JSP with an action and thus an Action class
Execute the query in Java code - you could do it in the Action, though I'd recommend passing control to a separate data access layer
Save the results of the query into a List of a bean type that holds each of the columns in your result
Set the List as an attribute of the request
Use a tag library like to loop over the the List, and print the output.
You can write your own jsp tags or you can use JSTL. JSTL is a standard tag library provided by oracle (originally sun)