jsf - @ViewScoped 在每次回发时创建新实例

标签 jsf jsf-2 postback view-scope

我有以下托管 bean。但每次我在调用 updateFileList 时都会向同一个 bean 发回邮件。我得到了 FileDAO 的一个新实例。

如何防止这种情况发生? 在托管 bean 中使用 DAO 是否安全,如果不安全,我可以进行哪些更改来改进它。

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

}

谢谢!

最佳答案

通常根本不应该在回发时重新创建 View 范围的 JSF 托管 Bean。

然而,这会在特定情况下发生,所有这些都与Mojarra issue 1492中描述的先有鸡还是先有蛋的问题有关。 (顺便说一句,这已针对即将推出的 Mojarra 2.2 进行了修复)。当您绑定(bind)标签处理程序的属性(如 JSTL <c:forEach>)时,将重新创建 View 作用域 bean View 作用域 bean 的属性,或者当您使用 JSF 组件时 binding View 范围 bean 的属性。解决方案是使用 JSF 组件而不是 JSTL 标记,并避免使用 binding在比请求范围更广的 bean 上。

另请参阅

关于jsf - @ViewScoped 在每次回发时创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8728414/

相关文章:

java - primefaces数据表过滤问题

jsf-2 - <c :if> Tag does not reduce the component tree in composite components

ASP.NET/DataList 的 DataItem 回发后为空

jsf - 如何更改 p :datatable dynamically 的延迟加载的 setRowCount

java - 当 session 超时时如何显示错误消息 glassfish 安全性?

validation - JSF 复合组件验证

c# - ASP.NET 按钮 options.clientSubmit 设置为 false

javascript - 无法在继承的 ASP.Net RadioButtonList 上使用 Javascript 清除所选项目

java - 嵌套的 forEach 循环 (JSTL/JSF)

jakarta-ee - 找不到工厂 : javax. faces.application.ApplicationFactory