我的 JSF 页面底部有一个提交按钮,用于将所有输入(文本、文件等)提交到数据库和服务器。由于此操作所需的持续时间,我想向用户显示操作的进度,并在完成后将他重定向到完成站点。
我的 bean 看起来像:
<h:form enctype="multipart/form-data">
<p:commandButton widgetVar="submitButton" value="Save to DB" action="#{bean.submit}" onclick="PF('submitButton').disable();" />
<p:progressBar widgetVar="pbAjax" ajax="true" value="#{bean.saveProgress}" interval="1000" labelTemplate="{value}%" styleClass="animated" />
</h:form>
和我的代码:
private int saveProgress;
public String submit(){
for(int i = 0; i < 100; i++){ //dummy values
//DB operations
//file uploads
saveProgress = i;
System.out.println("Progress: " + saveProgress);
}
return "finished.xhtml";
}
//getter for saveProgress
问题是,完成后进度条和页面都不会更新到finished.xhtml。
我在这里做错了什么?这是线程问题吗(因为提交不是线程安全的?)
我怎么解决这个问题?
最佳答案
这个解决方案(使用异步)是一个黑客,但它的工作原理:
<p:commandButton id="executeButton" action="#{myBean.longOperation}"
async="true" process="@form" value="start import"
onclick="progress.start()" global="false" />
<br />
<p:progressBar ajax="true" widgetVar="progress" value="#{myBean.progress}"
labelTemplate="{value}%" styleClass="animated" global="false" />
<br />
<p:outputPanel id="result" autoUpdate="true">
<h:outputText value="#{myBean.message}" />
</p:outputPanel>
用这种 bean
@ManagedBean
@ViewScoped
public class MyBean implements Serializable
{
private static final long serialVersionUID = 1L;
private double progress = 0d;
private String message = "ready";
public String longOperation() throws InstantiationException, IllegalAccessException
{
for(int i = 0; i < 100; i++)
{
// simulate a heavy operation
progress++;
message = "processing [" + i + "]";
Thread.sleep(1000);
}
message = "completed";
return "result";
}
public double getProgress()
{
return progress;
}
public void setProgress(double progress)
{
this.progress = progress;
}
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
}
关于jsf primefaces 进度条更新值,而 Action 方法正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756945/