Вопрос

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.

Это было полезно?

Решение

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'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(); 
    }

    ...

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top