how to return two lists from controller class in spring mvc

3.1k views Asked by At

I have two tables call maintab,subtab for generate menubar.

maintab has 

maitabId ,main_tab_name

subtab has:
sub_tb_ID  ,main_tb_id,subtab_name ,Url

I want to get two list containig list1=maintabid & maintabname

list2=subtabname,maintabID & url

I want to return the two list using spring mvc. And retrieve in jsp page to populate a menu.Please give me a code of controller class and jsp: i use hibernate and tile to this sample.

i tired

public String listmaintabAndsubtabs(Map<String, Object> map) {

        map.put("maintab", new maintab());
        map.put("maintabList", contactService.listmaintab());

        return "maintab";
    }

how to to return subtabs and main tabs both by one method....

2

There are 2 answers

1
Saurabh Jhunjhunwala On BEST ANSWER

Why do you want to return only a list, use map instead.

In your controller you can use,

Map mp = new HashMap();

mp.put("list1", lst1);
mp.put("list2", lst2);

return mp;

in your jsp, you can iterate the map,

for (Map.Entry<> entry : mp.entrySet()) {
    String listKey = entry.getKey();
    List<> childLst = entry.getValue();
}

EDIT :

Once you have two list, you can iterate them, in multiple ways,

you can use

for (X obj: childLst) { // X indicates the class of object the list contains System.out.println(obj); }

you can also use iterator to loop through the list.

0
A.v On

One way to do this is to have an dto. Dto pattern is when your data doesn't fit in your approach towards them. So you can have a class like this

public class MenuDto {
      private List list1;
      private List list2;          

      your accessor method for list1 & list2
}

And then your method in controller can just pass out an instance of MenuDto.