java - 通过omnifaces ViewScoped多次调用PreDestroy方法

标签 java jsf primefaces omnifaces

初始请求处调用PostConstruct方法。但是,当我上传图像时,有多个调用 PreDestroy 方法。 这意味着,每个 FileUploadEventImageActionBean View ID 都发生了变化。正如我认为 ViewID 在重定向到另一个页面之前不会改变, 我尝试清除上传文件的临时存储。

如果我上传三个图像,则第四次调用 PreDestroy 方法。这就是为什么我至少得到一个文件。

我的环境

- JBoss 7.1.1 Final
- primefaces-4.0-20130910.075046-7
- omnifaces-1.7.jar
- jboss-jsf-api_2.1_spec-2.0.5.Final.jar

堆栈跟踪:

>>>>> Initialization Finished
>>>>> Destroy Finished
>>>>> Destroy Finished
>>>>> Destroy Finished
>>>>> Destroy Finished


<h:form id="attachmentForm" enctype="multipart/form-data">
    <p:fileUpload fileUploadListener="#{ImageActionBean.handleProposalAttachment}"  
                mode="advanced" multiple="true" sizeLimit="3000000" update="attachmentTable"
                allowTypes="/(\.|\/)(gif|jpe?g|png)$/" id="proposalAttachment"/>

</h:form>

@ManagedBean(name = "ImageActionBean")
@ViewScoped <-- org.omnifaces.cdi.ViewScoped
public class ImageActionBean implements Serializable {
    private List<String> fileList;

    @PostConstruct
    public void init() {
        fileList = new ArrayList<String>();
        System.out.println("Initialization Finished");
    }

    @PreDestroy
    public void destory() {
        // clear uploaded file from temp storage
        System.out.println("Destroy Finished");
    }

    public List<String> getFileList() {
        return fileList;
    }

    public void handleProposalAttachment(FileUploadEvent event) {
        UploadedFile uploadedFile = event.getFile();
        String fileName = uploadedFile.getFileName().replaceAll("\\s", "_");
        fileList.add(fileName);
        //save uploadedFile to temp storage
    }
}

最佳答案

The OmniFaces CDI @ViewScoped 设计为与 CDI 托管 Bean 一起使用,而不是与 JSF 托管 Bean 一起使用。 @ManagedBean创建 JSF 托管 Bean,而不是 CDI 托管 Bean。 JSF 托管 bean 工具不支持 CDI 托管 bean 作用域,但仅支持 JSF 托管 bean 作用域。当没有人明确声明时,则默认范围 @RequestScoped实际会用到。

实际上,您的 bean 是一个请求作用域的 bean,这完全解释了您所观察到的症状。

为了利用 OmniFaces CDI @ViewScoped正确的方法是,通过替换 @ManagedBean 使您的 bean 成为真正的 CDI 托管 bean通过@Named .

@Named
@ViewScoped
public class ImageActionBean implements Serializable {
<小时/>

与具体问题无关,以大写字母开头的实例变量名称完全违反 Java naming conventions 。您实际上基本上是这样做的:

ImageActionBean ImageActionBean = new ImageActionBean();

这是绝对不推荐的。相反,你应该有效地做

ImageActionBean imageActionBean = ImageActionBean();

将 EL 变量更改为 #{imageActionBean}相应地。

关于java - 通过omnifaces ViewScoped多次调用PreDestroy方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21249417/

相关文章:

未显示 primefaces 消息

jsf - 标题中带有垂直文本的数据表

internet-explorer - IE 无法通过 WebSphere 提供的 SSL 下载文件

java - 通过支持 bean 的数据表行选择单一设置无法正常工作

jsf - Primefaces FileUpload 事件未触发 - JSF 2.0

java - identity.logout() 之后出现 ViewExpiredException;在 JBoss 中

java - 2015 年 6 月 30 日闰秒期间在 Amazon Linux AMI 上运行的日历操作

java - 从相机 Intent 中获取位图图像作为缩略图。如何让它变大

java - KafkaConsumer.close() 为什么?

java - 线程模板