how to get the element of a list inside jsp using JSTL? - spring

I have such this code inside my Spring MVC java controller class:
#RequestMapping(value = "jobs", method = { RequestMethod.GET })
public String jobList(#PathVariable("username") String username, Model model) {
JobInfo[] jobInfo;
JobStatistics js;
LinkedList<JobStatistics> jobStats = new LinkedList<JobStatistics>();
try {
jobInfo = uiClient.getJobs(username);
for (int i = 0; i < jobInfo.length; i++) {
js = uiClient.getJobStatistics(jobInfo[i].getJobId());
jobStats.add(js);
}
model.addAttribute("jobs", jobInfo);
model.addAttribute("jobStats", jobStats);
}
which uiClient will get some data from database using RMI ...
now I want to show the jobs & related statistic inside my JSP file using JSTL :
<c:set var="stats" value="${jobStats}" />
<c:forEach var="jobs" items="${jobs}">
<c:set var="jobID" value="${jobs.JobId}"/>
<table>
<tr class="tr1">
<td>${jobs.Topic}</td>
<td>${stats.get(i).No}</td>
</tr>
</table>
</c:forEach>
How do I get the LinkedList elements of Model inside my JSP using JSTL? There might be no no counter i been put in scope for me.

In my opinion, the right answer is a combination of both of the answers you got:
use varStatus attribute of c:foreach tag
but:
"get" is not a jstl function.
<c:forEach var="jobs" items="${jobs}" varStatus="i">
<c:set var="jobID" value="${jobs.jobId}"/>
<table>
<tr class="tr1">
<td>${jobs.topic}</td>
<td>${stats[i.index].no}</td>
</tr>
</table>
</c:forEach>
EDIT: this is the code finally used by the author of the question:
<c:set var="stats" value="${jobStats}" />
<c:forEach items="${jobs}" varStatus="i">
<c:set var="jobID" value="${jobs[i.index].jobId}"/>
<table>
<tr class="tr1">
<td>${jobs[i.index].topic}</td>
<td>${stats[i.index].no}</td>
<td>${jobID}</td>
</tr>
</table>
</c:forEach>

get is not a jstl function.
<td>${stats[i.index].No}</td>

use varStatus attribute of c:foreach tag
<c:forEach var="jobs" items="${jobs}" varStatus="i">
<c:set var="jobID" value="${jobs.JobId}"/>
<table>
<tr class="tr1">
<td>${jobs.Topic}</td>
<td>${stats.get(i.index).No}</td>
</tr>
</table>
</c:forEach>

Related

findAll() in spring boot

When I try to select all details of my database, I don't get data s into a table structure in my jsp page. The array is printed in my jsp but don't know how to make it single objects.
Here is my mapping
#RequestMapping("/viewall")
public ModelAndView findAll(ModelAndView mav){
List<aswathyDTO>li= dao.findAll();
for (aswathyDTO aswathyDTO : li) {
System.out.println(li);
}
mav.addObject("li",li);
mav.setViewName("li");
return new ModelAndView("displayall.jsp","li",li);
}
and here is my jsp page
<body>
${li }
<table>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<c:forEach items="${li}" var="li">
<tr>
<td>${li.id}</td>
<td>${li.name}</td>
<td>${li.age}</td>
</tr>
</c:forEach>
</table>
</body>
Your JSP should look like this:
<body>
<table>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<c:forEach items="${li}" var="element">
<tr>
<td>${element.id}</td>
<td>${element.name}</td>
<td>${element.age}</td>
</tr>
</c:forEach>
</table>
</body>
Also make sure that you import the standard library:
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

c:forEach does not print anything

I'm exploring spring mvc and I'm trying to print a list in a jsp file. Here the relevant parts of the code:
Controller
#Transactional
#RequestMapping("/homepage")
public String getHomePage(HttpServletRequest request, Model model) {
List<ProfessoreDAO> professori = (List<ProfessoreDAO>) sessionFactory
.getCurrentSession()
.createQuery("from ProfessoreDAO", ProfessoreDAO.class)
.getResultList();
System.out.println("Recuperati professori: " + professori);
model.addAttribute("professori", professori);
return "homepage";
}
jsp file:
<c:forEach var="professore" items="${professori}">
<tr>
<td>
${professore.nome}
</td>
<td>
<c:out value="${professore.cognome}" />
</td>
<td>
<c:out value="${professore.materia}" />
</td>
</tr>
</c:forEach>
At the moment I cannot debug on the server, but from what I see opening Firefox:
<c:foreach items="[Mario-Rossi]" var="professore">
</c:foreach>
It seems that the property is well defined ("Mario-Rossi" is just the toString implementation result of the only object present in the list) I've tried with both
<td> ${professore.nome} </td>
and
<td> <c:out value="${professore.cognome}" /> </td>
as you can see, but I've no results
as stated in the answer above I had forgotten to import the jstl support. To achieve this (I'm using tomcat 9, solution can slightly change depending on the tomcat version) I did:
pom.xml
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>1.2.6</version>
</dependency>
jsp file
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

How to show set of Arrays in one <TD> in Spring Boot / JSP?

I would like to show all the right answers(Green) in one TD if there are more than one and all the wrong answers(Red) in one TD if there are more than one. Is there anyway in the controller or at the front end that I can achieve this?
With my current code this is what I get.
The aim is to display like this
Controller
#GetMapping("/quesInAss/{id}")
public String quesInAssessment(#PathVariable("id") Integer id, Model model, HttpSession session) {
Integer insId = (Integer) session.getAttribute("instId");
List<Answers> rlist = new ArrayList<Answers>();
List<Answers> wlist = new ArrayList<Answers>();
Assessments ass = as.getAllByAssInst(id, insId);
model.addAttribute("assName", ass.getAssName());
List<Questions> queslist = qs.getQuesByAssessment(ass);
for (Questions ques : queslist) {
List<Answers> anslist = ansService.getAnswersByQuestion(ques);
for (Answers answer : anslist) {
if (answer.getAnsStatusCode().equals("CORR")) {
rlist.add(answer);
Answers[] array = new Answers[rlist.size()];
array = rlist.toArray(array);
model.addAttribute("rightAnsList", array);
} else {
wlist.add(answer);
Answers[] array = new Answers[wlist.size()];
array = wlist.toArray(array);
model.addAttribute("wrongAnsList", array);
}
}
}
model.addAttribute("queslist", queslist);
return "listOfQuesInAss";
}
JSP
<c:forEach items="${queslist}" var="ques">
<tr>
<td>${ques.quesText}</td>
<c:forEach items="${rightAnsList}" var="rightans">
<c:if test="${rightans.questions.quesId == ques.quesId}">
<td>${rightans.answer}</td>
</c:if>
</c:forEach>
<c:forEach items="${wrongAnsList}" var="wrongans">
<c:if test="${wrongans.questions.quesId == ques.quesId}">
<td>${wrongans.answer}</td>
</c:if>
</c:forEach>
</tr>
</c:forEach>
I'm not sure if I could understand your question right, try this:
<c:forEach items="${queslist}" var="ques">
<tr>
<td>${ques.quesText}</td>
<td>
<c:forEach items="${rightAnsList}" var="rightans" varStatus="status">
<c:if test="${rightans.questions.quesId == ques.quesId}">
${rightans.answer}
</c:if>
<c:if test="${not status.last}">,</c:if>
</c:forEach>
</td>
<td>
<c:forEach items="${wrongAnsList}" var="wrongans" varStatus="status">
<c:if test="${wrongans.questions.quesId == ques.quesId}">
${wrongans.answer}
</c:if>
<c:if test="${not status.last}">,</c:if>
</c:forEach>
</td>
</tr>
</c:forEach>

Why is <c:forEach> not working with Ajax request in JSP Spring?

I am fetching some data with a Ajax request in my main JSP page.
Snippet of main.jsp
function gu(){
$.get('/admin/getAllUsers', {}, function(data) {
console.log(data); // see below
$("#allUsersData").html(data);
});
}
In my Spring controller I add all the users to a different JSP page.
Snippet of MainController.java
#RequestMapping(value = "/admin/getAllUsers", method = RequestMethod.GET)
public String getAllUsers(Model model){
List<User> users = userRepository.findAll();
System.out.println(users.size()); // output: 3
model.addAttribute("allUsers", users);
return "data/all-users";
}
Now in all-users.jsp I have a <c:forEach> which is supposed to load all users in a html table:
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<c:if test="${not empty allUsers}">
<c:forEach items="${allUsers}" var="usr">
<tr>
<td>${usr.firstName}</td>
<td>${usr.lastName}</td>
<td>${usr.username}</td>
<td>${usr.creationDate}</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
However, when I add the html coming from the request to my main JSP page, an empty table is shown. When I log the result of the Ajax request I find that the user data is inserted in the all-users.jsp:
<c:if test="true">
<c:forEach items="[User{id=1, username='username1', firstName='John', lastName='Doe', roles=[Role{id=1, name='ROLE_USER'}], creationDate=2018-02-19T08:58:13.333}, User{id=2, username='username2', firstName='John2', lastName='Doe2', roles=[Role{id=3, name='ROLE_USER'}], creationDate=2018-02-19T08:58:13.471}]" var="usr">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</c:forEach>
</c:if>
Why is it happening that the data is loaded into the data JSP page, but not shown when appending it to the main JSP page?
Can you check, maybe you haven't included the core tag library in your JSP file.
You will do this by inserting the following Line at the top of your file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

ModelAttribute not working with lists in spring

I want to bind a List using ModelAttribute. The list contains objects of type Transaction each of which contains transactionid (type int). This is my controller code:
#RequestMapping(value = "/approvecreditdebit.do", method = RequestMethod.POST)
public ModelAndView doActions(HttpServletRequest request,
#ModelAttribute("clc") Clc transactionList, BindingResult result,
ModelMap model) {
/*
* switch (action) { case "approve":
*/
System.out.println("Obj = " + transactionList.getClass());
System.out.println("Val = " + transactionList.getTransactionList());
Users users = new Users();
return new ModelAndView("internal","internal",users);
}
This is my jsp code:
<form:form action="approvecreditdebit.do" method="POST"
modelAttribute="clc">
<table border="1">
<tr>
<th>no</th>
<th>ID</th>
</tr>
<c:forEach items="${clc.transactionList}"
var="transaction" varStatus="status">
<tr>
<td>${status.index}</td>
<td><input name = "transaction[${status.index}].transactionId"
value="${transaction.transactionId}" /></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<center>
<input type="submit" value="approve" />
</center>
</form:form>
This is the Clc class:
public class Clc{
private List<Transaction> transactionList;
public List<Transaction> getTransactionList() {
return transactionList;
}
public void setTransactionList(List<Transaction> transactionList) {
this.transactionList = transactionList;
}
}
The value of transactionList is not being set to the values received from the form. I receive the following error:
Request processing failed; nested exception is java.lang.NullPointerException
I tried searching for the solution on google and got a lot of solutions from stackoverflow but none of them seem to work.
Try something like this (notice the use of <form:input>). I just tried it on a simple Spring MVC app and it works (list is not null and has the values from the form when I try to access it in my POST method).
<c:forEach var="transaction" varStatus="status" items="${clc.transactionList}">
<tr>
<td>${status.index}</td>
<td><form:input path="transactionList[${status.index}].id" /></td>
</tr>
</c:forEach>

Resources