How to send List from Servlet to JSP

2019-03-02 02:15发布

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.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-03-02 02:38

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

request.setAttribute("postforUser", getPostforUser("komy"));
查看更多
对你真心纯属浪费
3楼-- · 2019-03-02 02:50

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>
<%}%>
查看更多
登录 后发表回答