Looping through a list of lists using JSTL - java

I have a list of courses depending on school code. This list of courses is added to another list, making it a list-of-lists.
Action Class:
private List<String> schoolList;
private List<String> socList;
private List<String> sobList;
private List<String> sodList;
private List<String> genlist;
private List<List<String>> courseList = new ArrayList<List<String>>();
#Override
public String execute() {
FacultyManager fm = new FacultyManager();
schoolList = fm.getColumn("school_description", "school");
genlist = fm.getCoursesBySchoolCode("GEN");
sobList = fm.getCoursesBySchoolCode("SOB");
socList = fm.getCoursesBySchoolCode("SOC");
sodList = fm.getCoursesBySchoolCode("SOD");
courseList.add(genlist);
courseList.add(sobList);
courseList.add(socList);
courseList.add(sodList);
return SUCCESS;
}
JSP:
<c:forEach var="school" items="${schoolList}" varStatus="ctr">
<ul>
<li>${school}
<ul>
<c:forEach var="course" items="${courseList}">
<li>${course}</li>
</c:forEach>
</ul>
</li>
</ul>
</c:forEach>
Output
How do I make it so the output is:
GENERAL EDUCATION
DEPARTMENT OF GENERAL EDUCATION
SCHOOL OF BUSINESS
BSBA - FINANCIAL MANAGEMENT
BSBA - MARKETING AND ADVERTISING
... and so on.

You are iterating the whole list of courses in all schools over and over again, thus repeating the same output as if you called courseList.toString() method multiple times.
You should instead iterate over a concrete list of courses in a current school, which most likely (but nowhere stated in your question) depends on the current iteration index of the outer <c:forEach> loop. This is in turn captured in the index property of the exported ctr variable (that is zero-based) of the school list iteration index.
Thus, you should iterate over a specific list of the courseList list, depending on the current school. You can do this by calling courseList.get(ctr.index), assuming you are on EL2.2+.
This all yields:
<c:forEach var="school" items="${schoolList}" varStatus="ctr">
<ul>
<li>${school}
<ul>
<c:forEach var="course" items="${courseList.get(ctr.index)}">
<li>${course}</li>
</c:forEach>
</ul>
</li>
</ul>
</c:forEach>
That said, List<List<String>> does not sound as a good model choice. For instance, if you change insertion order you'll get the wrong courses in your view. Map<String, List<String>> construct fits better your domain model as it can be used to map school name to a list of course names unambiguously.
Another option to consider seriously is the usage of objects (you are doing OOP in the end). You should turn away from plain strings and move into objects domain. To start, investigate the following class hierarchy:
public class Course {
//...
private School school;
//...
}
public class School {
//...
private List<Course> courses;
//...
}

If you are trying to iterate the list inside the list , you can achive it by
<c:forEach var="school" items="${schoolList}" varStatus="ctr">
<ul>
<li>${school}
<ul>
<c:forEach var="course" items="${school}">
<li>${course}</li>
</c:forEach>
</ul>
</li>
</ul>
</c:forEach>
You need to iterate the inner list from the list you pass it to the jsp.
Update
In the case if you are using Map<String, List<String>> , you can iterate it as
<c:forEach var="school" items="${schoolList}" varStatus="ctr">
<ul>
<li>${school.key}
<ul>
<c:forEach var="course" items="${school.value}">
<li>${course}</li>
</c:forEach>
</ul>
</li>
</ul>
</c:forEach>
You can use the key and value to get the values from the Map

Related

Wicket : Add a list to a datatable

I have a list of object to display in a table with wicket.
Those object are composed of a String and an Array of String.
My problem is that i don't know how to add this array into my table. And second, i have some css that I need to apply to each of my String of the array, so each of them have to be on a different div/span/li.
Can it be a good idea to concatenate all those elements and add the "div" manually ?
Thank you for your help :)
I have been to obssesed with using a datatable. By using a list in a list it work just fine !
JAVA :
ListView<Profil> listProfil = new ListView<Profil>("listProfils", profils) {
protected void populateItem(ListItem<Profil> item) {
Profil tmpProfil = item.getModelObject();
item.add(new Label("libelle", tmpProfil.getLibelle()));
item.add( new ListView("listChamps", tmpProfil.getChamps()) {
protected void populateItem(ListItem item) {
item.add(new Label("libelleChamps", item.getModel()));
}
});
}
});
And the associate HTML template :
<tr wicket:id="listProfils">
<div class="row">
<td class="col-xs-4 col-md-3 col-lg-3 text">
<span wicket:id="libelle"></span>
</td>
<td class="col-xs-7 col-md-8 col-lg-8 text" colspan="3">
<span wicket:id="listChamps">
<span wicket:id="libelleChamps"
class="label label-default badge badge-tag" >Champs</span>
</span>
</td>
</div>
</tr >
As a good practice in Wicket, to build a Table in HTML that is being fed from a List, you need the following elements:
HTML
<table wicket:id="yourWicketIdOfDataTableObject">[table]
</table>
JAVA
A POJO (pojoObject) that represents each element (o regiser) of your table
A DataProvider (dataProviderObject) class that extends from SortableDataProvider<pojoObject, String>
You need to override the iterator(), size() and model() methods according to your needs.
A List<IColumn<pojoObject,String>> columnsObject
The above object will represent the colums of your table.
You could add columns as follows:
columnsObject.add(new PropertyColumn<pojoObject,String>(new Model<String>("nameOfTheColum"),pojoObjectPropertyName))
A DefaultDataTable tableObject:
DataTable<pojoObject, String> = new DefaultDataTable("yourWicketIdOfDataTableObject", columnsObject, dataProviderObject, NumOfColumns)
The above object will represent the table.
As you might see pojoObject wraped by columnsObject and dataProviderObject, and these two will be wrapped by tableObject at the end. Your array will be accessed in the iterator() method of the dataProviderObject, because it needs to retrieve the iterator of the list; The pojoObject that represent the each element of your actual list will be necessary (in case you don't have one yet)
At the end, you only need add tableObject in their Wicket Parent, as any other Wicket Component.

How to access a variable of two class in JSP loop

I've got two classes:
public Car
Integer number;
String name;
public Parking
Integer parkingNumber;
String address;
I sent to my JSP one List of Parking and one List of Car
List<Parking> parkingList= new ArrayList<Parking>();
List<Car> carList= new ArrayList<Car>();
but full of values(they are not important for the example)
Model.addAttribute("parkingList", parkingList);
Model.addAttribute("carList", carList);`
How can i access inside a loop(foreach) to a car->name of a car with a car->number = a defined Parking->parkingNumber (assume for example this is 5) ?
<c:forEach items="${parkingList}" var="park" varStatus="status">
<p> $carList[park.parkingNumber=5].name</p>
</c:forEach>
Is it correct?
Unluckly I can't use another Foreach because the car.name value must be wrote in the page only one time.
Below line in your code seems to be incorrect
<p> $car[park.parkingNumber=5].name</p>
Because you are setting below values in model
Model.addAttribute("parkingList", parkingList);
Model.addAttribute("car", car);
where you are putiing single Car object in model and you are trying to access it like an array $car[park.parkingNumber=5].name
You can directly say car.name
Try this,
<c:forEach items="${parkingList}" var="park" varStatus="parkStatus">
<c:forEach items="${carList}" var="car" varStatus="carStatus">
<c:if test="car.number eq park.parkingNumber">
<p><c:out value="car.name" /></p>
</c:if>
</c:forEach>
</c:forEach>
OR
If you do not wish to use multiple foreach loops, on server side, you can use Car class in Parking class like,
public Parking
Integer parkingNumber;
String address;
List<Car> carList = new ArrayList<>();
And put the Car's list in the Parking object where all cars having same number as parkingNumber.
for(Parking parking : parkingList) {
for(Car car : carList) {
if (car.getNumber() == parking.getParkingNumber()) {
parking.getCarList().add(car);
}
}
}
Then you have to just iterate this once and you will get all the cars which has same parking number.
<c:forEach items="${parkingList}" var="park" varStatus="parkStatus">
<c:forEach items="${park.carList}" var="car" varStatus="carStatus">
<p><c:out value="car.name" /></p>
</c:forEach>
</c:forEach>

How to iterate map values which are in the form of lists in jsp?

public class Students()
{
private String title;
private String name;
//getters setters
}
I have a map
Map<String,List<Students>> mapList
What i want to is, i send a key to get value from map and iterate that lists.
My approach
jsp
<c:forEach items="${mapList['${title}']}" var="actualDetails">
//printing the values
</c:forEach>
You can't do EL expressions inside EL expressions.
It's already an EL expression, so it should just be:
<c:forEach items="${mapList[title]}" var="actualDetails">
Suppose ${mapList} points to a Map<String,List<Students>>, then you can use the following EL expressions
<c:forEach items="${mapList}" var="entry">
${entry.key}<br>
<c:forEach items="${entry.value}" var="studentDetails">
${studentDetails.title}<br>
${studentDetails.name}<br>
</c:forEach>
</c:forEach>

Print multiple values on a JSP page by struts property tag

I am trying to print the various values received from an database in action class to a JSP page by s:property tag. However it is showing only one value.
ACTION CLASS:
ResultSet r = st.executeQuery("select unique(emailid) from pagequery");
while (r.next()) {
uniquemail=r.getString(1);
}
JSP PAGE:
The JSP page should show all the unique email id's. But it is showing only the first one.
<td>
<s:property value="uniquemail"/>
</td>
Here
while (r.next()) {
uniquemail=r.getString(1);
you are overriding a single variable with the new value on every iteration. You need to use a List or an array, and add new elements to it, otherwise you will always have only the last iterated value stored.
public class YourAction exteds ActionSupport{
private List<String> mails = new ArrayList<String>();
/* put Getter and Setter for mails here */
public String execute(){
/* ... other stuff here ... */
ResultSet r = st.executeQuery("select unique(emailid) from pagequery");
while (r.next()) {
mails.add(r.getString(1));
}
return SUCCESS;
}
}
Then use an iterator in JSP to render your collection.
Mails:
<ul>
<s:iterator value="mails">
<li><s:property/></li>
</s:iterator>
</ul>
If uniquemail is an array you have to iterate through it like this
<s:iterator value="uniquemail">
<s:property/>
</s:iterator>

how to print arraylist object value in jsp page [duplicate]

I have two arraylists in my class and I want to send it to my JSP and then iterate the elements in arraylist in a select tag.
Here is my class:
package accessData;
import java.util.ArrayList;
public class ConnectingDatabase
{
ArrayList<String> food=new ArrayList<String>();
food.add("mango");
food.add("apple");
food.add("grapes");
ArrayList<String> food_Code=new ArrayList<String>();
food.add("man");
food.add("app");
food.add("gra");
}
I want to iterate food_Code as options in select tag and food as values in Select tag in JSP; my JSP is:
<select id="food" name="fooditems">
// Don't know how to iterate
</select>
Any piece of code is highly appreciated. Thanks in Advance :)
It would be better to use a java.util.Map to store the key and values instead of two ArrayList, like:
Map<String, String> foods = new HashMap<String, String>();
// here key stores the food codes
// and values are that which will be visible to the user in the drop-down
foods.put("man", "mango");
foods.put("app", "apple");
foods.put("gra", "grapes");
// if this is your servlet or action class having access to HttpRequest object then
httpRequest.setAttribute("foods", foods); // so that you can retrieve in JSP
Now to iterate the map in the JSP use:
<select id="food" name="fooditems">
<c:forEach items="${foods}" var="food">
<option value="${food.key}">
${food.value}
</option>
</c:forEach>
</select>
Or without JSTL:
<select id="food" name="fooditems">
<%
Map<String, String> foods = (Map<String, String>) request.getAttribute("foods");
for(Entry<String, String> food : foods.entrySet()) {
%>
<option value="<%=food.getKey()%>">
<%=food.getValue() %>
</option>
<%
}
%>
</select>
To know more about iterating with JSTL here is a good SO answer and here is a good tutorial about how to use JSTL in general.
<c:forEach items="${list}" var="foodItem">
${foodItem.propertyOfBean}
</c:forEach>
This will solve your problem.
You can use JSTL's foreach.
<c:forEach items="${foodItems}" var="item">
${item}
</c:forEach>
You need also to import JSTL core:
<%# taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
You can retrieve the list in JSP as
<select id="food" name="fooditems">
<c:forEach items="${listname}" var="food" >
<option value="${food}"> ${food} </option>
</c:forEach>
</select>
There are multiple ways this can be done (with some changes in your scheme)
Using JSTL:
Create a bean with two fields as food and food_code
public class Food{
private String food;
private String food_code;
// Setter/getters follows
}
Now the arraylist available on the page will be list Food objects.
In the JSP code, you can use following:
<select name="fooditems">
<c:forEach items="${list}" var="item">
<option value="${item.food_code}">${item.food}</option>
</c:forEach>
</select>
If you are using struts:
<html:select property="fooditems" >
<html:optionsCollection property="list" label="food" value="food_code" />
</html:select>
Here list is object key which will be used to retrieve the list from context (page/session)

Categories

Resources