2
votes

I am having the below managed bean. But every time I do a post back to the same bean ie while calling updateFileList. I get a new instance of FileDAO.

How can I prevent this? Is it safe to have a DAO inside a managed bean, if not what changes can I make to better it.

@ManagedBean(name = "file")
@ViewScoped
public class FileController implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<LoadFileLog> fileList = null;
    private Date selectedDate;
    FileDAO fileDAO;

    public FileController() {

        System.out.println(" In file Controller constructor");
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        fileDAO = (FileDAO) context.getBean("FileDAO");


    }


    public FileDAO getFileDAO() {
        return fileDAO;
    }





    public void setFileDAO(FileDAO fileDAO) {
        this.fileDAO = fileDAO;
    }





    public List<LoadFileLog> getFileList() {

        return fileList;

    }

    public Date getSelectedDate() {
        return selectedDate;
    }

    public void setSelectedDate(Date selectedDate) {
        this.selectedDate = selectedDate;
    }

    public void updateFileList() {

        SystemController systemControl = (SystemController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("system");
        List systemList = new ArrayList();

        if (systemControl != null) {
            systemControl.populateSelectedSystems();
            systemList = systemControl.getSelectedSysIdList();
        }

        if (selectedDate != null) {
            fileList = getFileDAO().getFiles(systemList, selectedDate);
        }
    }

}

Thanks!

2

2 Answers

5
votes

A view scoped JSF managed bean should normally not be recreated on postbacks at all.

This will however happen in specific circumstances, all related to the chicken-egg issue as described in Mojarra issue 1492 (which is fixed for the upcoming Mojarra 2.2 by the way). A view scoped bean will be recreated when you're binding attributes of tag handlers like JSTL <c:forEach> to a property of the view scoped bean, or when you're using JSF component binding to a property of the view scoped bean. The solution would be to use JSF components instead of JSTL tags and to avoid using binding on a bean of a broader scope than the request scope.

See also

0
votes

What is a bean scope of fileDAO?

It would be better to get spring inject that dependency without getting application context from servlet one and then retrieving bean from it.