英文:
how to send multiple ArrayList from a Servlet to JSP without using JSTL
问题
我必须从Servlet将三个ArrayList发送到jsp页面。
我的问题是,我无法从同一个方法返回三个ArrayList。
public ArrayList<A> afficher(String s) {
    ArrayList<A> list = new ArrayList<A>();
    ArrayList<B> list2 = new ArrayList<B>();
    //一些操作
    list.add(new A("aaa"));
    list2.add(new B("bbbb"));
    // 如何继续进行?
}
英文:
I have to send three ArrayList from the servlet to jsp.
My problem is i cannot return three arrayList from the same method.
public ArrayList afficher(String s)
ArrayList <A> list = new ArrayList<A>();
ArrayList <B> list2 = new ArrayList<B>();
//some operations
list.add(new A("aaa"));
list2.add(new B("bbbb"));
return list, list2;
ow can I proceed?
</details>
# 答案1
**得分**: 1
你可以将变量存储为[ServletContext](https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html)中的属性,并在你的JSP中检索它们。有关详细信息,请参见这个[之前的问题](https://stackoverflow.com/questions/22049414/store-variable-for-jsp-usage)。
<details>
<summary>英文:</summary>
You can store variables as attributes in [ServletContext](https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html), and retrieve them in your JSP. See this [previous question](https://stackoverflow.com/questions/22049414/store-variable-for-jsp-usage) for details. 
</details>
# 答案2
**得分**: -1
```java
可以创建一个返回类型为ModelAndView的方法。
   ModelAndView mav = new ModelAndView();
   mav.setViewName("welcomePage");
   mav.addObject("list", list);
   mav.addObject("list2", list2);
   return mav;
在该mav对象中,您可以添加任意数量的模型。
在jsp上,您可以使用`${list}, ${list2}`来访问它们。
@Data
@Builder
class Main {
   public List<List<Object>> getList() {
       List<List<Object>> list = new ArrayList<>();
       list.add(Arrays.asList(new A[]{new A("A"), new A("A1"), new A("A2")}));
       list.add(Arrays.asList(new B[]{new B("B"), new B("B1"), new B("B2")}));
       return list;
   }
}
class A {
   String name;
   public A(String name) {
       this.name = name;
   }
}
class B {
   String name;
   public B(String name) {
       this.name = name;
   }
}
英文:
You can create your method with ModelAndView as return type.
ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("list", list);
mav.addObject("list2", list2);
return mav
In that mav object you can add n number of models.
And on jsp you can access them using ${list}, ${list2}.
@Data
@Builder
class Main {
    public List<List<Object>> getList() {
        List<List<Object>> list = new ArrayList<>();
        list.add(Arrays.asList(new A[]{new A("A"), new A("A1"), new A("A2")}));
        list.add(Arrays.asList(new B[]{new B("B"), new B("B1"), new B("B2")}));
        return list;
    }
}
class A {
    String name;
    public A(String name) {
        this.name = name;
    }
}
class B {
    String name;
    public B(String name) {
        this.name = name;
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论