在初始请求
处调用PostConstruct
方法。但是,当我上传图像时,有多个调用 PreDestroy
方法。
这意味着,每个 FileUploadEvent
的 ImageActionBean
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/