Akila Adithya
Akila Adithya

Reputation: 1

How to return multiple variables from method?

Here I'm getting data from database and put those data into different ArrayLists. I need to pass all those array lists to jsp page.How can I pass multiple ArrayLists , this is my code,

 package ConnectionPack;
 import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.Connection;
 import java.util.ArrayList;

 import com.mysql.jdbc.Statement;

 public class DBConnection {
  String DB_URL="jdbc:mysql://localhost:3306/bbc";
  String DB_Username="root";
  String DB_Password="";
  String sql ="select * from news";
  Connection con = null;


ArrayList<String> para=new ArrayList<String>();
ArrayList<String> link=new ArrayList<String>();
ArrayList<Integer> image=new ArrayList<Integer>();

public ArrayList data(){
    ArrayList<String> li=new ArrayList<String>();
    ArrayList<String> li1=new ArrayList<String>();
    ArrayList<String> li2=new ArrayList<String>();
    ArrayList<Integer> li3=new ArrayList<Integer>();
    try{
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(DB_URL,DB_Username,DB_Password);  
        Statement statement = (Statement) con.createStatement();
        ResultSet resultset = statement.executeQuery(sql);

        while(resultset.next()){
            String headdata = resultset.getString("Title");
            li.add(headdata);

            String paradata = resultset.getString("Description");
            li1.add(paradata);

            String linkdata = resultset.getString("Link");
            li2.add(linkdata);

            int imagedata = resultset.getInt("id");
            li3.add(imagedata);
        }   
    }catch(Exception e){
        e.printStackTrace();
    }
    return li;
}
    //close the connection

}

I need to pass this 'li','li1','li2','li3' to JSP page, How can I do this?

Upvotes: 0

Views: 64

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272297

It looks to me that you have a requirement to pass back a list of news e.g. define a class called News (containing your title, id etc.) and return List<News>.

Note that this enforces some type safety over returning (say) a list of list of strings. You could go further and return a NewsList (which itself contains a List<News> and the ability to iterate over this - or whatever other functionality you require - rendering, perhaps?)

Don't be shy about creating such objects. They give you type safety and the ability to encapsulate behaviour and content.

Upvotes: 1

Related Questions