purplewind purplewind - 26 days ago 16
Java Question

How to display arraylist objects in jsp using session.getAttribute

I am trying to display the objects in an ArrayList defined in my servlet in the jsp file using session.getAttribute() to retrieve the ArrayList.

<%= String name= (String[]) session.getAttribute("studentObject"); %>


This is my current code in the jsp display file and the error says "Syntax error, insert ")" to complete MethodInvocation". The syntax looks okay to me. Any idea what the error is ?

I defined an ArrayList which consists of student objects which I wanna display. This is how I retrieved it:

String student_name = request.getParameter("studentName");
ArrayList<Object[]> studentList = new ArrayList<Object[]>();
if(student_name != null && student_name.length() > 0) {
PreparedStatement preparedStatement = con.prepareStatement("Select * from users where firstname LIKE ? ");
preparedStatement.setString(1, "%" +student_name+ "%");
ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
String first_name = resultSet.getString("firstname");
String last_name = resultSet.getString("lastname");
String email = resultSet.getString("email");

Object[] student = {first_name,last_name,email};
studentList.add(student);
//System.out.println("First Name: " + first_name + "," + "Last Name: " + last_name);
}
session.setAttribute("studentObject",studentList);
//System.out.println(Arrays.toString(studentList.get(0)));

Answer
<%= String name= (String[]) session.getAttribute("studentObject"); %>

your declartion is wrong in here. you assigned your session.getAttribute("studentObject") into a string of Array. your session.getAttribute("studentObject") is an ArrayList thats why you got it wrong. Remove the equal sign <%= on your scriplet because you are on declaration phase.

Just change it to this:

<% ArrayList<Object[]> name= (ArrayList<Object[]>)session.getAttribute("studentObject"); %>

And if you wanna get the array of student list in your arraylist. See below:

<% for(Object[] tempStudentList: name) {
    System.out.println(tempStudentList[0],tempStudentList[1],tempStudentList[2]);
} %>

you cannot cast it to array of String because array of Object can have different data type on its element. You can cast the Object to String in every element when you retrieve it. here is the Sample:

<% for(Object[] tempStudentList: name) {
    for(Object tempStudent : tempStudentList) {
         String student = (String) tempStudent;
         System.out.println(student);
    }
} %>