I'm using Struts2+Hibernate. I have a form in a JSP page, in which there is a select that I need to populate it from Database. I have implemented the DAO class BookDAO ( selectBooks(), updateBook(Book book)). I have created the Action class in which I declared an ArrayList of Book, and an object of class BookDAO. It seems that I need to define a function in the Action class which call selectBooks and populate my ArrayList, But this action should be called automatically on loading my JSP page. Is Ajax necessary in my case? Thank you.
Asked
Active
Viewed 1,706 times
2 Answers
1
JB Nizet's answer is good, I would suggest a slightly different approach however.
The problem with putting the ArrayList assignment in the execute method is that it will only work for that particular method and needs to be recreated if other action methods are added.
You are better off making the action Preparable and adding a prepare method to do all your database calls and list assignments. This way all your data will be avalable throughout the action class without having to duplicate code along the way.
The prepare method will be called first, before any other in the action.
public class MyAction extends ActionSupport implements Preparable{
private ArrayList<Books> books;
@Override
public void prepare() throws Exception {
this.books = bookDAO.selectBooks();
}
...
}

Russell Shingleton
- 3,176
- 1
- 21
- 29
-
Thank you! Sometimes I think at a complicated way till getting lost. I was thinking in redirecting the action and so on. But here it's simple and useful. Thank you! – Jul 25 '12 at 17:19
0
No, AJAX is not necessary. In the code of your action method, initialize the list:
public String execute() {
this.books = bookDAO.selectBooks();
return SUCCESS;
}
The JSP page will then have access to the list of books.

JB Nizet
- 678,734
- 91
- 1,224
- 1,255
-
Thank you a lot for this answer. Although simple, it works fine for me! So gonna make an upvote for you and for Russell and mark it as resolved :) – Jul 25 '12 at 17:22