【发布时间】:2009-06-06 03:30:47
【问题描述】:
我正在使用 JSP、JSTL、Servlet 和 JavaBeans 编写网站。
在我的代码中,我尝试使用对象的 ArrayList,但发生了一件奇怪的事情:当我添加第一个对象时它很好,当我添加第二个对象时它会在第二个对象中添加它位置,但 index(0) 处的对象与 index(1) 处的对象获得相同的值。
可能问题出在
ArrayList<Article> articleList = new ArrayList<Article>();
Article newArticle = new Article();
由于articleList是Article类的ArrayList。
谁能指出我做错了什么?
下面是我的代码:
public ArrayList<Article> getArticles()
{
baseIO mySql = new baseIO();
ArrayList<Article> articleList = new ArrayList<Article>();
int articleId = 0;
try
{
String sql =
"select * from jsp_blog_article order by article_id Desc Limit 3";
con = (Connection)mySql.getConnection();
pstmt = (PreparedStatement) con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Article newArticle = new Article();
newArticle.setArticleAuthor(rs.getString("article_name"));
newArticle.setArticleBody(rs.getString("article_body"));
newArticle.setArticleAuthor(rs.getString("article_author"));
newArticle.setArticleDate(rs.getString("article_date"));
articleId = Integer.parseInt(rs.getString("article_id"));
newArticle.setArticleId(String.valueOf(articleId));
newArticle.setArticleComments(this.getCommentsNum(articleId));
articleList.add(newArticle);
}
con.close();
pstmt.close();
}
catch(Exception e)
{
return null;
}
return articleList;
}
还有文章类
package objects;
import java.io.Serializable;
public class Article implements Serializable{
private String articleName;
private String articleBody;
private String articleAuthor;
private String articleComments;
private String articleDate;
private String articleId;
public Article()
{
}
// all the getters and setters in place, but it is too long
// so i am not going to post them in forum
}
【问题讨论】:
-
您首先解析 articleId 然后立即将其转换回字符串的任何特殊原因?
-
是复制粘贴getArticles()方法还是你的真实代码略有不同?因为您的代码和 Soldier.moth 的代码之间应该没有功能差异。你每次都在创建一个新的 Article 对象,就像他一样。
-
我其实也很好奇,因为回首往事,我不确定为什么我的代码在你的代码中没有工作。
-
mmyers,articleId 在 mysql 数据库中是整数,在文章对象中是字符串。当我编写我的代码时,它看起来是正确的,但是 Soldier.moth 的代码有效,而我的无效。数组列表返回到另一个 javabean 并从那里返回到我用 jstl foreach 标记显示它的 jsp 页面。
-
articleId 如何存储在数据库中并不重要。上面的代码从数据库中读取一个字符串(JDBC 驱动程序为您将整数转换为字符串),然后您将字符串转换为 int。然后将 int 转换回字符串。只需使用:newArticle.setArticleId(rs.getString("article_id"));