我想在提交文件之前要求用户输入密码。所以在点击“提交”按钮后应该呈现<h:panelGroup>
。但是,永远不会呈现<h:panelGoup>
。
test.xhtml
<ui:define name="body">
<h:form id="uploadForm" enctype="multipart/form-data">
<table>
<t:inputFileUpload id="uploadedFile" storage="file"
value="#{UpdateBean.uploadedFile}"/>
<h:commandButton value="Submit" action="#{UpdateBean.submit()}"/>
</table>
</h:form>
<h:panelGroup id="checkPassword" rendered="#{UpdateBean.submitIsPerformed}">
<h:outputText id="message" value="${UpdateBean.message}" />
<h:inputText id="password" value="#{UpdateBean.password}" />
<h:commandButton value="submit" action="#{UpdateBean.submitPassword()}"/>
</h:panelGroup>
</ui:define>
UpdateBean.java
@ManagedBean(name = "UpdateBean")
@SessionScoped
public class UpdateBean {
protected boolean submitIsPerformed = false;
protected String password = "";
protected String message = "Input your password ";
// omit getter and setter
public void submit() {
this.setSubmitIsPerformed(true);
System.out.println(submitIsPerformed); // output is true
while(true) {
if(password.equals("123")) {
break;
}
}
// then process uploadedFile
}
public void submitPassword(){
if(password.equals("123")) {
message = "Password confirmed !";
} else {
message = "Password is wrong !";
}
}
}
答案 0 :(得分:2)
您的错误在于submit()
方法:
while(true) {
if(password.equals("123")) {
break;
}
}
while(true)
阻止操作方法返回。只要操作方法没有返回,服务器就不会使用更新的视图返回HTTP响应。实际上,您的服务器CPU之一被限制在100%,客户端无限期地等待HTTP响应。您应该通过检查浏览器的进度指示器(如果有的话)注意到它。
你应该在切换布尔值后立即返回:
public void submit() {
submitIsPerformed = true;
}
使用submitPassword()
方法执行密码检查和上传文件保存。但是,由于这不是相同的形式,上传的文件将丢失。即使你把它放在同一个表格中,也会上传两次。但这是一个不同的问题。我建议反过来做这个工作。
答案 1 :(得分:0)
按照@BalusC的建议,这是我的更新代码。
test.xhtml
<ui:define name="body">
<h:form>
<h:commandButton value="Upload a file" action="#{UpdateBean.submit()}">
<f:ajax render=":checkPassword" />
</h:commandButton>
</h:form>
<h:form id="checkPassword" styleClass="toggle" rendered="#{UpdateBean.submitIsPerformed}">
<table>
<tr>
<td><h:outputText value="Password" /></td>
<td><h:inputText id="password" value="#{UpdateBean.password}" /></td>
<td>
<h:commandButton value="Submit" action="#{UpdateBean.submitPassword()}">
<f:ajax execute="password" render=":uploadFile" />
</h:commandButton>
</td>
</tr>
</table>
</h:form>
<h:form id="uploadFile" enctype="multipart/form-data"
styleClass="toggle" rendered="#{UpdateBean.uploadFileIsPerformed}">
<t:inputFileUpload id="uploadedFile" storage="file"
value="#{UpdateBean.uploadedFile}">
</t:inputFileUpload>
<h:commandButton value="Submit" action="#{UpdateBean.uploadFile()}" />
</h:form>
</ui:define>
UploadBean.java
public String submit() {
setSubmitIsPerformed(true);
return "SUCCESS";
}
public String submitPassword(){
if(password.equals("123"){
setUploadFileIsPerformed(true);
setSubmitIsPerformed(false);
}
return "SUCCESS";
}
public String uploadFile(){
return "SUCCESS";
}