list 如何将列表从 Servlet 发送到 JSP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25962218/
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
How to send List from Servlet to JSP
提问by Dmitry Mahliui
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.
我List<PostData>
在 Servlet 中为用户发布了一些帖子,如何将此列表发送到用户的 JSP 页面?我需要拆分服务器部分和布局部分。谢谢。
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.
一切正常,我在下面做了连接和其他事情。
回答by Sas
You can set the list in your attribute and loop throught it on ur jsp.
您可以在您的属性中设置列表并在您的 jsp 上循环遍历它。
request.setAttribute("posts", posts);
In your jsp:
在你的jsp中:
<table>
<c:forEach items="${posts}" var="post">
<tr>
<td>${post.id}</td>
....
</tr>
</c:forEach>
</table>
Without jstl, would be something like this:
没有jstl,会是这样的:
<%
ArrayList<PostData> posts=(ArrayList<PostData>) request.getAttribute("posts");
for (PostData post: posts) {
%>
<tr>
<td><%=post.id%></td>
....
</tr>
<%}%>
回答by Roman C
Use request scope attribute, then you can access it with JSP EL via ${postforUser}
.
使用请求范围属性,然后您可以使用 JSP EL 通过${postforUser}
.
request.setAttribute("postforUser", getPostforUser("komy"));