c:forEach does not print anything - spring

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" %>

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" %>

Why do am I getting error "java.lang.IllegalStateException" after putting <form:form> tag in jsp file of spring?

I have 2 tables, city and hotel_details in my database. I am trying to fetch the data from these tables and populating inside a form for registering the customer. But I am getting "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute" as error.
JSP file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<head>
<title>Search Hotels</title>
</head>
<body>
<h4>Search Hotels</h4>
<form:form action="search">
<table>
<tr>
<td>City:</td>
<td>
<form:select path="cities">
<form:options items="${cities}" />
</form:select>
</td>
</tr>
<tr>
<td>Hotel:</td>
<td>
<form:select path="hotels">
<form:options items="${hotels}" />
</form:select>
</td>
</tr>
<tr>
<td>Date:</td>
<td>
<input type="date" id="date" name="date">
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Check Availability">
</td>
</tr>
</table>
</form:form>
Controller
#Controller
public class HomeController {
//need a controller method to show the initial HTML form
#Autowired(required=true)
private CityDAO cityDAO;
#Autowired(required=true)
private HotelDetailsDAO hotelDetailsDAO;
#RequestMapping("/")
public String showCheckAvailablityForm(Model theModel) {
// get customers from the dao
//List<City> theCities = cityDAO.getCities();
List<String> theCities = cityDAO.getCities();
Set<String> theHotels = hotelDetailsDAO.getHotels();
// add the customers to the model
theModel.addAttribute("cities", theCities);
theModel.addAttribute("hotels", theHotels);
//printing the data fetched
System.out.println("In HomeController showCheckAvailability method where city name is being fetched from city table");
theCities.forEach((n) -> System.out.println(n));
System.out.println("printing hotels");
for (String temp : theHotels) {
System.out.print(temp + " ");
}
return "checkAvailability-form";
}
#RequestMapping("/search")
public String searchResult(#RequestParam("cityName") String theCityName, #RequestParam("hotelName") String theHotelName,Model model) {
System.out.println("processed successfully");
return null;
}
}
When you use <form:form> attribute, it requires you to specify model object that should be bound to form tag. If you don't specify any model attribute default name is used as command.
Following is the description of form:form tag from spring-form.tld -
<attribute>
<description>Name of the model attribute under which the form object is exposed.
Defaults to 'command'.</description>
<name>modelAttribute</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Name of the model attribute under which the form object is exposed.
Defaults to 'command'.</description>
<name>commandName</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
As you don't have any model object bound to form, try removing form:form tag and use HTML form tag and also make sure you match input parameter names with method parameter names. i.e -
<form action="search">
...
</form>

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" %>

Spring form validation - errors are not displayed

I have following situation:
I try to create a simple form to edit information about a movie. Therefor I use spring mvc with jsp.
For the validation I use the JSR 303 hibernate implementation (hibernate-validator 4.2.0).
My problem is that if there are validation errors (BindResults hasErrors method returns true) I can only display the errors with
<form:errors path="*" />
and not fieldspecific. like with:
<form:errors path="title" />
I have no idea why but all errors are displayed in at the path="*" errortag, but none at the fieldspecific ones. The only errors which are displayed right to the field are some which brought an exception i.e.
Failed to convert property value of type java.lang.String to required type int for property runtime; nested exception is java.lang.NumberFormatException: For input string: "")
the important parts of my jsp file look like this:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form commandName="movie">
<fieldset>
<form:errors path="*" cssClass="formErrorBlock"/>
<table>
<tr>
<td><form:label path="title">Title:</form:label></td>
<td>
<form:input path="title"/>
<form:errors path="title" cssClass="formFieldError"/>
</td>
</tr>
<tr>
<td><form:label path="runtime">Runtime:</form:label></td>
<td>
<form:input path="runtime"/><br />
<form:errors path="runtime" cssClass="formFieldError" />
</td>
</tr>
<tr>
<td><form:label path="imdbId">IMDB-ID:</form:label></td>
<td>
<form:input path="imdbId"/><br />
<form:errors path="imdbId" cssClass="formFieldError" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" />
</td>
</tr>
</table>
</fieldset>
</form:form>
My Controller:
#Controller
public class MovieController {
#Autowired
private MovieService _movieService;
//some other methods...
#RequestMapping(value="/movie/{pMovieId}/edit", method = RequestMethod.GET)
public String showForm(ModelMap pModel, #PathVariable Integer pMovieId) {
Movie movie = _movieService.getMovieById(pMovieId);
pModel.addAttribute("movie", movie);
return "edit/movie";
}
#RequestMapping(value="/movie/{pMovieId}/edit", method = RequestMethod.POST)
public String editMovieSave(#Valid Movie pMovie, BindingResult pResult, #PathVariable Integer pMovieId, ModelMap pModel) {
Movie movie = _movieService.getMovieById(pMovieId);
if(pResult.hasErrors()) {
return "edit/movie";
}
//save
//redirect to moviepage
return "redirect:/movie/" + pMovieId;
}
}
and finally my movie class:
public class Movie implements Serializable{
private int _id;
#NotEmpty
#Size(min=3)
private String _title;
#NotEmpty
private String _filename;
#Pattern(regexp="tt+[0-9]{7}")
private String _imdbId;
#Min(value=1)
private int _runtime;
//getters and setters....
}
I know this question has been asked a lot of times before, but none of the answers worked with me.
thanks for your help
I solved it by renaming the attributes (removing the underlines). However it was like "jpprade" said (maybe there are accessed by reflection).
For those who can't rename the class attributes (in case of some codingconventions, ...) can annotate the getter methods.

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

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>

Resources