4

I want to send array of my own objects to JSP page by request.

At this part of code in servlet I'll get my data, put it on array of objects, and set them to request.

     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;
  }

This is my class:

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;
}
}

On my JSP page, I want to loop such array of objects using request.getAttribute("articles"); How I can do it?

I must use <jsp:useBean/> or something else? I tried to do this way:

Article[] articles = request.getAttribute("articles");

But I have an error: Article cannot be resolved to a type

What I did wrong?

Elber CM
  • 310
  • 5
  • 21
Anton Sementsov
  • 1,196
  • 6
  • 18
  • 34

3 Answers3

11

You should avoid using of scriptlets by using JSTL. Please go through the following example:

An example of POJO class:

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;
    }

}

An Example of 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);
    }

}

An example of JSP-page:

<%@ 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>

The result 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>

I hope that example could help you.

Dmytro Chyzhykov
  • 1,814
  • 1
  • 20
  • 17
  • thanks for example... But i have a question: when i write it on JSP `` my loop know, ${articles} data been sending from servlet by request, not by other ways... or i should note somewhere it, or initialize a variable `articles` – Anton Sementsov Feb 20 '12 at 14:11
  • on scope? do something like that scope="request" – Anton Sementsov Feb 20 '12 at 14:31
  • yes, on scope. There are 4 scopes in JSP/Servlet API: 1) application - the global one [ServletContext](http://bit.ly/xChDI5) 2) session - one per HTTP session [HttpSessionContext](http://bit.ly/zkPokb) 3) request - one per Request [ServletRequest](http://bit.ly/wMhTt5) 4) page - one per each page that handle request [PageContext](http://bit.ly/A0Btl8) It's up to you to chose an appropriated one that meets your needs. See a good material about this topic - [What are the different scopes in JSP?](http://bit.ly/aNUu7i) – Dmytro Chyzhykov Feb 20 '12 at 15:35
3

You probably

  • forgot to import the Article class in the JSP, using <%@ page import="com.foo.bar.Article" %>
  • forgot to cast the result of getAttribute() to an array of articles:

Article[] articles = (Article[]) request.getAttribute("articles");

Note that you shouldn't have any Java code in a JSP. You should use the JSP EL, the JSTL, and other custom tags. Read How to avoid Java code in JSP files?.

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2
request.getAttribute("articles");

The above will always return String so you need to do a cast, use this

Article[] articles = (Article[]) request.getAttribute("articles");

and import your Article class in your jsp page, add this at the import level

<%@ page import="yourpackage.Article"%>
subodh
  • 6,136
  • 12
  • 51
  • 73