我想根据请求将我自己的对象数组发送到JSP页面。将servlet对象数组发送到JSP
在servlet中的这部分代码中,我将获取我的数据,将它放在对象数组中,并将它们设置为请求。
if (request.getParameter("todo").equals("show_article_list")) {
try {
Article[] articles = this.getArticleList();
request.setAttribute("articles", articles);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("article/article_list.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
}
}
public Article[] getArticleList() throws Exception {
db data = new db();
Connection con = data.OpenConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM `article`");
ResultSet result = statement.executeQuery();
int size = 0;
if (result != null)
{
if (result.last()) {
size = result.getRow();
result.beforeFirst();
}
}
Article[] articles = new Article[size];
int i = 0;
while(result.next()){
articles[i] = new Article (
result.getInt(1),
result.getString(2),
result.getString(3),
result.getString(4));
i++;
}
return articles;
}
这是我的课:
public class Article {
public Integer getId(){return id;}
public String getTitle(){return title;}
public void setTitle(String title){this.title = title;}
public String getText(){return text;}
public void set(String text){this.text = text;}
public String getDescription(){return description;}
public void setDescription(String description){this.description= description;}
private Integer id;
private String title;
private String text;
private String description;
public Article(Integer Id, String Title, String Text, String Description)
{
id = Id;
title = Title;
text = Text;
description = Description;
}
}
在我的JSP页面,我想用循环对象request.getAttribute("articles");
这样的阵列我该怎么办呢?
我必须使用<jsp:useBean/>
还是别的?我试图做的是这样的:
Article[] articles = request.getAttribute("articles");
但我有一个错误:Article cannot be resolved to a type
我做了什么错?
谢谢例如...但我有一个问题:当我在JSP上写入时''c:forEach items =“$ {articles}”var =“article”>'我的循环知道,$ {articles}数据是通过请求从servlet发送的,而不是其他方式...或者我应该注意它的位置,或初始化一个变量'articles' – 2012-02-20 14:11:15
的范围?做一些像那样的范围=“请求” – 2012-02-20 14:31:46
是的,范围。 JSP/Servlet API中有4个范围: 1)应用程序 - 全局范围[ServletContext](http://bit.ly/xChDI5) 2)会话 - 每个HTTP会话一个[HttpSessionContext](http:// bit.ly/zkPokb) 3)请求 - 每请求一个[ServletRequest](http://bit.ly/wMhTt5) 4)页 - 处理请求[PageContext](http:// bit。 ly/A0Btl8) 您可以选择适合您需求的拨款电话。 查看关于此主题的好资料 - [JSP中有哪些不同的范围?](http://bit.ly/aNUu7i) – 2012-02-20 15:35:39