I am trying to pass an ArrayList that I have created to a JSP page but I am having a difficult time attempting to do this. Here is what I have so far.
Java Class:
public class Main {
private ArrayList<Employee> employees = new ArrayList<Employee>();
public Main (){
try{
BufferedReader br = new BufferedReader(new FileReader("lang.txt"));
String line;
String[] employee;
Employee employeeObject;
br.readLine();
while ((line = br.readLine()) != null) {
employee = line.split(",");
employeeObject = new Employee (employee[0], employee[1], employee[2], employee[3], employee[4], employee[5], employee[6]);
employees.add(employeeObject);
}
br.close();
}
catch(IOException e){
}
}
/**
* @return the employees
*/
public ArrayList<Employee> getEmployees() {
return employees;
}
/**
* @param employees the employees to set
*/
public void setEmployees(ArrayList<Employee> employees) {
this.employees = employees;
}
}
JSP Page:
<%@page import="lab3final.beans.Employee"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="employee" scope="session" class="lab3final.beans.Main"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Table Data</title>
</head>
<body>
<h1>Data in text file in table format</h1><br>
<c:forEach items="${employee.employees}" var="item">
${item}<br/>
</c:forEach>
</body>
</html>
It would be great if someone could give me some idea on what I am doing wrong. I am not able to read the ArrayList I created on my JSP page.
UPDATE: I figured out the problem was that I had to give the full path to my text file lang.txt
otherwise it would be searching for the file in some other directory which was not my main project directory. I guess this is the default location for searching for files when I try to read files using a FileReader in the constructor of a class.
Right now I can print out all the employees using ${employee.employees}
and it will print out all the employees using the toString()
method I have defined in the employees class. I am still trying to figure out how I can use the loop function in JSP so I can loop through each individual employee.
call each variable of your employee class in your jsp page. Make sure that your employee object has all your necessary getter and setters. ${item.variable1}, ${item.variable2}
I figured out what the problem was. It was a silly mistake on my part. I forgot to add this line on top of the JSP page:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
This is why the forEach
loop did not work. Once I added that line to the top of my page, the loop worked perfectly fine and I was able to loop through each individual employee object. Thanks for your help guys!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.