0

I got an arrayList of BlogPosts and I want to show the content of the objects on screen.
I read my ArrayList from the ServletContext with this output:

 [com.example.week3.BlogPost@58d100c8, com.example.week3.BlogPost@5baade52]

Where and how do I read the content of this?

This is my BlogPost class:

package com.example.week3;

import java.io.Serializable;

public class BlogPost implements Serializable{
    private String blogtext;

    public BlogPost(String bt) {
       blogtext = bt;
    }

    public String getBlogtext() {
        return blogtext;
    }

}

This is where I store my List

Object o = getServletContext().getAttribute("blogpost");
Rover
  • 387
  • 4
  • 14

1 Answers1

0

It is using the default toString() method implementation of Object.

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So you are getting output like com.example.week3.BlogPost@58d100c8. When you iterate over the ArrayList you need to typecast it to your BlogPosts Object and use it getter methods or overridden toString() to display it's content.

You can do

    Object o = getServletContext().getAttribute("blogpost");

    if( o instanceof ArrayList) {
        List blogList = (ArrayList) o;
        for(Object blog : blogList){
            BlogPost blogPost = (BlogPost) blog;
            System.out.println(blogPost.getBlogtext());
        }
    }
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • I added my BlogPost class, can you help me out how to display all content of the blogposts? – Rover Jun 01 '14 at 13:59
  • Thanks! And can you tell me how I can display the results in my JSP page? – Rover Jun 01 '14 at 14:47
  • You can set it in the request as attribute , forward the request to JSP and the access it there. Google `pass data from servlet to JSP`. [Sample](http://stackoverflow.com/questions/5414600/pass-data-from-java-servlet-to-jsp). – Aniket Thakur Jun 01 '14 at 14:52