jsf - 从动作侦听器调用时,Getter 方法返回 null
问题描述
我有一个带有 ap:selectOneMenu 组件的应用程序。该组件用于确定上传文件的类别,以便在上传文件时对其进行一些处理。
我实现了这篇文章的答案,它似乎为 fileType 正确调用了我的 setter 方法。但是一旦文件被提交并且handleFileUpload方法被调用,fileType getter方法返回null。
例如,如果我选择 Foo 然后我得到输出
File type changed to: Foo
但是当我点击上传按钮时,我得到了输出
The file type selected is null
当我期待
The file type selected is Foo
是什么导致 get 方法返回两个不同的结果,有没有办法解决这个问题?
main.xhtml
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<meta http-equiv="refresh"
content="#{session.maxInactiveInterval};url=index.xhtml" />
<f:view contentType="text/html">
<h:head>
<title>File Upload</title>
</h:head>
<p:layout fullPage="true">
<p:layoutUnit position="center">
<ui:insert name="pagebody" />
</p:layoutUnit>
</p:layout>
</f:view>
</html>
索引.xhtml
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" template="/templates/main.xhtml">
<ui:define name="pagebody">
<h:body>
<h:form id="uploadform" enctype="multipart/form-data">
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<h:outputText value="File Type:" />
<p:selectOneMenu value="#{uploadBean.fileType}">
<f:selectItem itemLabel="Foo" itemValue="Foo"/>
<f:selectItem itemLabel="Bar" itemValue="Bar"/>
<f:ajax listener="#{uploadBean.changeFileType}" />
</p:selectOneMenu>
</h:panelGrid>
<br />
<p:fileUpload fileUploadListener="#{uploadBean.handleFileUpload}" mode="advanced"/>
</h:form>
</h:body>
</ui:define>
</ui:composition>
上传Bean.java
@RequestScoped
@ManagedBean(name = "uploadBean")
public class UploadBean implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String fileType = null;
@PostConstruct
public void init() {
}
public void handleFileUpload(FileUploadEvent event){
System.out.println("The file type selected is " + this.getFileType());
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public void changeFileType() {
System.out.println("File type changed to: " + this.getFileType());
}
}
解决方案
正如@Kukeltje 指出的那样,问题是我的 bean 没有正确限定范围。从 RequestScoped 切换到 ViewScoped 解决了我遇到的问题。
推荐阅读
- python - 从烧瓶项目同一目录中的 __init__ 导入
- amazon-web-services - CloudFront 标头未正确转发
- string - 如何识别字符串中编码的日期或日期和时间?
- java - 收到错误,因为“DesiredCapabilities 类型的方法 chrome() 未定义”
- azure - 在 Azure Active Directory 中使用 MS Graph API:C# 和 Postman
- apache-spark - 循环搜索算法
- c++ - 不同语言的浮点精度
- python - 使用 django 在 heroku 上创建超级用户时出错
- reactjs - 静默更新错误帧窗口在刷新令牌上超时
- python - 烧瓶全局python对象