如何使用java方法在jsp中打印arraylist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19133189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:23:33  来源:igfitidea点击:

how to Print arraylist in jsp using java method

javajsp

提问by user2837886

This is Java class:

这是Java类:

package com.example;

import java.util.ArrayList;

public class sample {

    public void print() {

        ArrayList<String> l = new ArrayList<String>();
        l.add("a");
        l.add("b");

    }
}

This is my Jsp page :

这是我的 Jsp 页面:

<%@page import="java.awt.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@ page import="com.example.sample"%>
<%@page import="java.util.*"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
    sample s = new sample();
%>


</body>
</html>

I dont know how to call print merhod and how Print list in jsp page so that i print data in jsp page list please help me how i will Implement i am learning this.

我不知道如何调用print merhod以及如何在jsp页面中打印列表,以便我在jsp页面列表中打印数据,请帮助我如何实现我正在学习这个。

采纳答案by Suresh Atta

First return a list from print method

首先从打印方法返回一个列表

public List<String> print() {

        ArrayList<String> l = new ArrayList<String>();
        l.add("a");
        l.add("b");

     return l;

    }

Don't use scriplets, Use JSTL

不要使用脚本,使用 JSTL

<%
    sample s = new sample(); //not recommended.Pass this object from servlet
    List<String> list = s.print();
%>

with that print where ever you want to print in jsp

使用该打印件在您想要打印的任何位置 jsp

With JSTL

JSTL

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

With scriplets (not recommended);

带脚本(不推荐);

<% for (int i=0;i<list.size();i++)
          {

              out.println(list.get(i));

          } %>

With help of iterator;

在的帮助下iterator

 <%  Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {    
        out.println(<iterator.next());
    }
 %>

Side note:Not tested ,and make sure that you have imported all used classes in JSP.

旁注:未测试,并确保您已在JSP 中导入所有使用的类。

回答by Chirag Kathiriya

<%
Class c = new Class(); 
List<String> list = c.print();
for (c : list) {
  //print list here
}
%>