How to send List from Servlet to JSP

2019-03-02 02:06发布

问题:

I have List<PostData> with some posts for user in Servlet , how can i send this list to user's JSP page?? I need to split the server part and layout part. Thanks.

This is my List:

public List<PostData> getPostforUser(String komy)
{
    ArrayList<PostData> posts = new ArrayList<PostData>();
    try {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("select * from posts where komy='"+komy+"'");
        while(rs.next())
        {
            PostData postdata = new PostData();

            postdata.setId(rs.getInt("id"));
            postdata.setOtkogo(rs.getString("otkogo"));
            postdata.setKomy(rs.getString("komy"));
            postdata.setText(rs.getString("text"));
            postdata.setDate(rs.getString("'date'"));
            posts.add(postdata);

        }
    }catch (SQLException e) {

        e.printStackTrace();
    }
    return posts;
}

All is work, i made Connections and another things below.

回答1:

You can set the list in your attribute and loop throught it on ur jsp.

request.setAttribute("posts", posts);

In your jsp:

<table>
  <c:forEach items="${posts}" var="post">
   <tr>
     <td>${post.id}</td>
     ....
   </tr>
  </c:forEach>
</table>

Without jstl, would be something like this:

<%
  ArrayList<PostData> posts=(ArrayList<PostData>) request.getAttribute("posts"); 
  for (PostData post: posts) {   
%>
  <tr>
    <td><%=post.id%></td>
    ....
   </tr>
<%}%>


回答2:

Use request scope attribute, then you can access it with JSP EL via ${postforUser}.

request.setAttribute("postforUser", getPostforUser("komy"));