Looping Arraylist of Arrays java

105 views Asked by At

I have a method in the model that creates an ArrayList array me from a resultset, I need is cross it from jsp, I could not do, any help?

This is the code of the arraylist

    public ArrayList listar(){

    String sql="select * from eventos";
    ArrayList lista=new ArrayList();
    try {
        st=con.createStatement();
        rs=st.executeQuery(sql);

        int NumColumnas=getRows(rs);

        while(rs.next()){
            String Fila[]=new String [NumColumnas];   
            for(int x=0;x<NumColumnas;x++){
                Fila[x]=rs.getObject(x+1).toString();
            }
             lista.add(Fila);
        }

    } catch (SQLException ex) {
        Logger.getLogger(EventosBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return lista;
}

From the jsp I have this code and I returned values in this format [Ljava.lang.String;@39dc94a4 [Ljava.lang.String;@5d013b69

    EventosBean ev=new EventosBean();
    ArrayList<EventosBean>arrayList=ev.listar();
    out.println(arrayList.size());
    Iterator<EventosBean> iterator = arrayList.iterator();
    while (iterator.hasNext()) {    
        out.println(iterator.next());
    }
2

There are 2 answers

1
Amit.rk3 On BEST ANSWER

Something is wrong. In your listar method, you are returning a ArrayList . This ArrayListcontains obejcts of type String[]. You are capturing this output in a ArrayList<EventosBean>, which expects objects of type EventosBean.

If you are looking to print content of the String[] added in listar returned ArrayList on JSP, make few changes in your code as shown below.

public ArrayList<String[]> listar(){

    String sql="select * from eventos";
    ArrayList<String[]> lista=new ArrayList<String[]>();
    try {
        st=con.createStatement();
        rs=st.executeQuery(sql);

        int NumColumnas=getRows(rs);

        while(rs.next()){
            String Fila[]=new String [NumColumnas];   
            for(int x=0;x<NumColumnas;x++){
                Fila[x]=rs.getObject(x+1).toString();
            }
             lista.add(Fila);
        }

    } catch (SQLException ex) {
        Logger.getLogger(EventosBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return lista;
}

and in your class where you are calling listar

EventosBean ev=new EventosBean();
ArrayList<String[]> arrayList=ev.listar();
out.println(arrayList.size());
for(String[] strArray : arrayList){
    String str="";
    for(String str1: strArray)
      str=str+" "+str1;

    out.println(str);
}
1
Diego Furtado On

You need to set the attribute in http servlet request and use this in your jsp:

/** Java Controller*/

request.setAttribute("events", lista);

/** JSP */

List<String> events = (List<String>) request.getAttribute("events");