java - 将对象数组从 servlet 发送到 JSP

标签 java jsp servlets

我想根据请求将我自己的对象数组发送到 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

我做错了什么?

最佳答案

您应该通过使用 JSTL 来避免使用 scriptlet。 请通过以下示例:

POJO 的例子类:

public class Article {
    private int id;
    private String title;

    public Article(int id, String title) {
        this.id = id;
        this.title = title;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

Servlet 示例:

public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Article[] articles =
                new Article[] {new Article(1, "Article one"), new Article(2, "Article two")};
        request.setAttribute("articles", articles);

        RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
    }

}

JSP 页面示例:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <c:forEach items="${articles}" var="article">
    <c:out value="${article.id} ${article.title}"/><br />
  </c:forEach>
</body>
</html>

结果 HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    1 Article one<br />

    2 Article two<br />

</body>
</html>

希望这个例子能帮到你。

关于java - 将对象数组从 servlet 发送到 JSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9360223/

相关文章:

java - 为什么 httpServletRequest.getLocalPort 总是返回与 getServerPort 相同的值?

java - 在Java中减去两个日期

java - 在不同的 Java Web 项目之间共享表示逻辑

java - fmt :message default value

使用 MultipartConfig 的 Java Servlet

java - 用程序理解java中的交换函数

java - 如何在 OrientDB 中使用 Java 删除远程图

jsp形式的Java UTF-8编码

servlets - web xml 在 session 配置跟踪模式下显示错误

java - 如何使用参数初始化 Java EE 5 JAX-WS 2.0 Web 服务