如何在jsp中显示java中的ArrayList项?

问题描述 投票:0回答:2

我已经生成了一个Arraylist,我逐行从数据库中获取项目。我想在jsp中显示值,但我不知道如何将jsp绑定到java。

在java类中,listBook是BookBean类型的Arraylist。

BookDao课程:

public  ArrayList<BookBean> listBooks = new ArrayList<>();

....

System.out.println(listBooks.get(0).getId()); ->display id of first row
System.out.println(listBooks.get(0).getTitle()); ->display title of first row
System.out.println(listBooks.get(0).getAuthor());

在我的Controller类中,我有:

    public String showBooks(Model bookModel){
        bookModel.addAttribute("bookAttribute", new BookDao());
        return "book-list";
    }

我想通过使用Controller中的模型在jsp中打印listBook的结果。我怎样才能做到这一点?

BookDao:
public  ArrayList<BookBean> listBooks = new ArrayList<>();
 public void generateBookList() {
        try {
            Connection connection = ConnectToDatabase.createConnection();
            if (connection != null) {
                PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from book ");
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    BookBean bookBean = new BookBean(resultSet.getInt("id_book"), resultSet.getString("title"), resultSet.getString("author"), resultSet.getString("publishDate"), resultSet.getInt("quantity"), resultSet.getString("bookPrice"));
                    listBooks.add(bookBean);
                } }
        } catch (Exception e) {
            e.printStackTrace();
        }}

BookController打开jsp页面“book-list.jsp”:

@Controller
public class BookController {
    @RequestMapping("/showBooks")
    public String showBooks(Model bookModel){
        bookModel.addAttribute("bookAttribute", new BookDao());
        return "book/book-list";
    }
}

我想通过控制器中创建的模型访问jsp中的“listBooks”。我在想jstl,但我无法相应地编写代码。

java mysql jsp jstl
2个回答
1
投票

你可以使用jstl核心标签<c:forEach>。如果你需要在你的列表上循环,你可以这样做:

在BookController中将列表传递给模型:

 model.addAttribute("bookList", yourList);

在JSP中:

...
<c:forEach items="${bookList}" var="book"> 
${book.id}  <%-- BookBean fields that you want print out--%>
${book.title}
<%-- another fields --%>
</c:forEach>
...

see official oracle documentation for more detail


0
投票

在JSP页面上,只需执行以下操作:

<%
   out.println(listBooks.get(0).getId()); ->display id of first row
   out.println(listBooks.get(0).getTitle()); ->display title of first row
   out.println(listBooks.get(0).getAuthor());
%>
© www.soinside.com 2019 - 2024. All rights reserved.